简体   繁体   中英

Calling Web Service .asmx from javascript using ajax

I have implemented a pop-up in an asp.net web app which allows the user to select something and an email template is generated. After completing all the required fields, the user sends the email by the click of a button.

This button calls a javascript function where I gather all the user input data like from, to, subject, body and want to send this data to a web service I have created which will send the mail.

I didn't want to use mailto, so I went with web service.

The problem is that I can't send the data:

$.ajax({
            type: 'POST',
            url: "Services/MailService.asmx/SendMail",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            data: { 'loginName': "'" + loginName + "'", 'fromAddress': "'" + fromAddress + "'", 'toAddress': "'" + toAddress + "'", 'mailSubject': "'" + mailSubject + "'", 'mailBody': "'" + mailBody + "'"},
            success: function ()
            {
                alert("The email was sent successfully!");
            },
            error: function(data)
            {
                alert("An error occurred while trying to send the email. " + data.responseText);
            }
        });

I know that what I inserted in the data property is wrong. I have tried the following, (one at a time):

data: JSON.stringify({ 'loginName': loginName, 'fromAddress': fromAddress, 'toAddress': toAddress, 'mailSubject': mailSubject, 'mailBody': mailBody }),
data: { 'loginName': loginName, 'fromAddress': fromAddress, 'toAddress': toAddress, 'mailSubject': mailSubject, 'mailBody': mailBody },
data: { loginName: loginName, fromAddress: fromAddress, toAddress: toAddress, mailSubject: mailSubject, mailBody: mailBody },
data: "{ 'loginName': '" + loginName + "', 'fromAddress': '" + fromAddress + "', 'toAddress': '" + toAddress + "', 'maliSubject': '" + mailSubject + "', 'mailBody': '" + mailBody + "' }",

All these options give me the following errors:

An error occurred while trying to send the email. {"Message":"Invalid web service call, missing value for parameter: \u0027mailBbody\u0027.","StackTrace":"   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

or

An error occurred while trying to send the email. {"Message":"Invalid JSON primitive: loginName.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

I don't understand what I'm doing wrong.

The web service looks like this:

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    public void SendMail(string loginName, string fromAddress, string toAddress, string mailSubject, string mailBody)
    {
        MailMessage mailMsg = new MailMessage(fromAddress, toAddress);
        mailMsg.Subject = mailSubject;
        mailMsg.Body = mailBody;

        string pathToCreate = "~/Upload/" + loginName + "/";
        if (Directory.Exists(Server.MapPath(pathToCreate)))
        {
            if (Directory.GetFiles(Server.MapPath(pathToCreate)).Length > 0)
            {
                string[] attachedFiles = Directory.GetFiles(Server.MapPath(pathToCreate));
                foreach (string a in attachedFiles)
                {
                    Attachment data = new Attachment(a);
                    mailMsg.Attachments.Add(data);
                }
            }
        }

        SmtpClient smtp = new SmtpClient();
        smtp.Send(mailMsg);
    }
}

Please share with me what could I do to solve this issue.

Thank you!

I was able to successfully send the data by using:

data: '{loginName:' + JSON.stringify(loginName) + ', fromAddress:' + JSON.stringify(fromAddress) + ', toAddress:' + JSON.stringify(toAddress) + ', mailSubject:' + JSON.stringify(mailSubject) + ', mailBody:' + JSON.stringify(mailBody) + '}',

I don't know if this is the right way but it's working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM