成功回调在$ .getJSON中无效

时间:2013-03-18 10:05:49

标签: asp.net json web-services cross-domain

我有一个我想要调用的跨域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);
        }

    }    
}

以下是萤火虫追踪的回应。 enter image description here

任何人都可以告诉我可能是什么问题。

1 个答案:

答案 0 :(得分:0)

最有可能因为您的网络服务位于外部域,这是一个跨网域问题。 你必须使用 jsonp

你可以看看这里 - Basic how-to for cross domain jsonp