0

呼び出したいクロスドメイン 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>

これが私のWebサービスコードです。

<%@ 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);
        }

    }    
}

以下は、firebug でトレースされた応答です。 ここに画像の説明を入力

何が問題なのか誰か教えてください。

4

1 に答える 1

0

ほとんどの場合、Web サービスは外部ドメインにあるため、クロスドメインの問題です。これにはjsonpを使用する必要があります。

ここで見ることができます-クロスドメインjsonpの基本的なハウツー

于 2013-03-18T10:13:08.033 に答える