我有一个我想调用的跨域 web 服务,但是当我尝试调用它时,我在 json 中得到了正确的响应(在 firebug 中检查)但成功回调永远不会触发,而是执行错误回调。
这是我的 JavaScript 代码。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON("http://[external domain]/Service.asmx/SendMail?callback=?", { 'body': txtEmail.value }, function (data) {
alert("SUCCESS");
})
.error(function (data) { alert("ERROR: " + data.responseText); })
});
});
</script>
这是我的网络服务代码。
<%@ WebService Language="C#" Class="Service" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Net.Mail;
using System.Web.Script.Serialization;
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[ScriptService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SendMail(string body)
{
Context.Response.Clear();
Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
Context.Response.ContentType = "application/json";
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
MailMessage message = new MailMessage();
message.From = new MailAddress("[senders mail]");
message.To.Add("[recepient mail]");
message.IsBodyHtml = true;
message.Priority = MailPriority.High;
message.Subject = "[subject]";
message.Body = body;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("[username]", "[password]");
client.Send(message);
string str = "{\"value\" : \"sent\"}";
// also tried with JavascriptSerializer like in catch block, that too not working.
Context.Response.Flush();
Context.Response.Write(str);
}
catch(Exception ex)
{
string str = js.Serialize(ex.Message);
Context.Response.Flush();
Context.Response.Write(str);
}
}
}
以下是萤火虫中追踪的响应。
谁能告诉我可能是什么问题。