![](/img/trans.png)
[英]Getting error in calling web service using ajax in jquery +jquery mobile?
[英]Calling Web Service from jQuery .ajax() issue
我在跨域調用Web服務時遇到問題。 我在這里讀過一些文章,但是我並沒有真正找到解決方案。 我剛剛了解到我需要數據的json
格式,因為我總是遇到Error: Access denied.
嘗試從服務獲取xml
數據時,但是現在我遇到了另一個問題。 這是我的.ajax()
調用:
$.ajax({
type: "GET",
contentType: "application/jsonp; charset=utf-8",
url: "http://tomas/_vti_bin/EmmaService.asmx/GetResult",
dataType: "jsonp",
data: {
value : "testValue",
converstionId : "testId"
},
success: function(resp) {
alert("success: " + resp);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error status: " + xhr.status);
alert("error status text: " + xhr.statusText);
alert("error response text: " + xhr.responseText);
},
});
從這我得到以下3個警報的錯誤:
error status: 200
error status text: success
error response text: undefined
我不明白的是error status text: success
。
我的網絡服務中的代碼:
[WebMethod(EnableSession = false, Description = "Gets result")]
public EmmaServiceResult GetResult(string value, string converstionId)
{
...
return result;
}
關於如何使它工作的任何建議? 謝謝! :)
嘗試添加?callback=?
到您的網址末尾:
http://tomas/_vti_bin/EmmaService.asmx/GetResult?callback=?
另外,嘗試查看thrownError以確定錯誤是什么:
alert("error response text: " + thrownError);
這可能是解析錯誤等。實際上與ajax請求無關,但與如何定義響應處理方式有關。
另外,請查看此處以了解如何從WCF服務返回json。
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "players")]
最近,我在處理來自AJAX調用的跨域請求時遇到了很多問題。 我們最終無需修改API就可以使它工作,但是我們確實需要訪問托管API的服務器,因此我們可以讓它在響應中發送一些標頭。 但是整個問題讓人難以調試,而且我發現所有瀏覽器都無法報告有意義的錯誤。 因此,如果這不能解決您的問題,則可能對您不起作用,並提前道歉。
該解決方案要求您發出CORS請求,並向服務器響應中添加一些標頭。 這些頁面都是不錯的資源:
https://developer.mozilla.org/zh-CN/docs/HTTP/Access_control_CORS http://www.html5rocks.com/zh-CN/tutorials/cors/
我認為在您的情況下,由於您正在發出基本請求並且不處理Cookie,因此您可以保持.ajax調用基本不變,只要將dataType更改為“ json”,將contentType更改為“ application / json”正在發送JSON。
然后,您必須修改服務器,以通過將以下標頭添加到響應中來使其處理CORS預檢請求:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type
(請參閱此問題: jQuery CORS Content-type OPTIONS )
希望這對您有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.