2013-03-18 25 views
0

我有一個跨域web服務,我想調用,但是當我嘗試調用它時,我在json(在螢火蟲中選中)得到了正確的響應,但成功回調從未激發,相反,它執行錯誤回調。

這是我的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); 
     } 

    }  
} 

下面是在螢火蟲追蹤到的反應。 enter image description here

誰能告訴我可能是什麼問題。

回答

0

很可能是因爲您的Web服務位於外部域中,這是跨域問題。 您必須爲此使用jsonp

你可以看看這裏 - Basic how-to for cross domain jsonp

+0

感謝您的答覆,但我已經使用了回調=?因爲它是一個跨域,在這種情況下,它應該工作,我是否失去其他任何東西。 – Abbas 2013-03-18 10:17:03

+0

您需要在服務級別設置JSONPBehavior。查看http://archive.msdn.microsoft.com/DataServicesJSONP – Dinesh 2013-03-18 10:26:44