2014-04-02 134 views
1

我主持一个Web服务让跨域Web服务调用未返回预期的结果

http://example1.com/webservice.asmx

,并希望从

http://example2.com

叫我有jQuery的准则像example2.com

GetData: function() { 
    $.ajax({ 
     crossDomain: true, 
     type: "POST", 
     url: "http://example1.com/webservice.asmx/GetData", 
     dataType: "jsonp", 
     contentType: "application/json; charset=utf-8", 
     data: { Date: '' }, 
     success: function (data, textStatus, jqXHR) { 
      debugger;     
     }, 
     error: function (data, textStatus, jqXHR) { 
      alert("data"); 
     } 
    }); 
    } 

it像

http://example1.com/webservice.asmx/GetData?callback=jQuery19106349606812515739_1396429620115&Date=&_=1396429620116 

它使用GET方法(从萤火虫)击​​中该网址。实际上哪里是我无法找到它的问题。它以XML格式响应数据。 并且还以XML格式响应数据但未成功事件。 但它工作正常,如果我把相同的代码在同一个域。

+1

您的webservice是否包装响应与回调?例如'jQuery19106349606812515739_1396429620115({'iam':'json response'});'? –

+0

不,我不知道从哪里jQuery19106349606812515739_1396429620115 被添加到请求服务的URL。 – manoj

+0

你知道dataType:“jsonp”是什么意思吗? –

回答

0

对于JSONP,您的响应必须包含在Javascript函数中。如果您设置了dataType: "jsonp",jquery会自动向GET-URL添加一个回调参数。这个回调参数是一个随机的js函数名称,您的ajax请求需要恢复数据交叉原点。

为了使它工作,你需要改变你的web服务,如下所示:

  1. 变化JSON
  2. 缠上回调参数的响应。例如,在VB.NET:

    Dim returnVal=Request.Param("Callback") & "(" & jsonreturn & ");" 
    Response.Write(returnVal) 
    

请参见本post的细节,让它与你的web服务ASMX工作。另外,您可以将您的Web服务更改为CORS

0

此修补程序适用于JQuery的纯json调用。 的System.Web内启用HTTPGET和后从你的web.config

<webServices> 
    <protocols> 
    <add name="HttpSoap"/> 
    <add name="HttpPost"/> 
    <add name="HttpGet"/> 
    <add name="HttpPostLocalhost"/> 
    </protocols> 
</webServices> 

之后,您Global.asax文件创建一个方法,以使横域通信(vb.net) “== ==================== EnableCrossDmainAjaxCall =================

Private Sub EnableCrossDmainAjaxCall() 
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*") 

    If HttpContext.Current.Request.HttpMethod = "OPTIONS" Then 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS") 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept") 
     HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000") 

     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "origin, x-requested-with, content-type") 
     HttpContext.Current.Response.[End]() 
    End If 

End Sub 

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) 
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache) 
    HttpContext.Current.Response.Cache.SetNoStore() 
    EnableCrossDmainAjaxCall() 
End Sub 
'==========================