通过jQuery调用ASMX Web服务时遇到了麻烦。我可以在浏览器中粘贴此URL以获取所需的XML结果:
http://<serverurl>/WebService/ReportServer.asmx/RowDataWithFilterParamsAndColumnParams?filterParams=EXCAVATION_DIG.EXCAVATION_DIG_INTL_ID%20IN%20(1)&columnParams=Dig_ID|Line|Dig_Type|Dig_Status
我可以从这样的控制台应用程序中调用asmx而不会出现任何问题:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Credentials = new NetworkCredential("username", "pass");
req.PreAuthenticate = true;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
我遇到的麻烦是从客户端调用Web服务。我的代码出了什么问题?我没有得到任何错误,但没有调用成功函数。
$( document ).ready(function() {
var url = "http://<serverurl>/WebService/ReportServer.asmx/RowDataWithFilterParamsAndColumnParams";
var payload = "{ filterParams : 'EXCAVATION_DIG.EXCAVATION_DIG_INTL_ID%20IN%20(1)', columnParams : 'Dig_ID|Line|Dig_Type|Dig_Status' }";
$.ajax({
type: "POST",
url: url,
data: payload,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
});
当我将数据类型更改为“json”时,我收到错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
答案 0 :(得分:0)
这是CORS(跨域资源共享)错误 - 基本上,浏览器中的脚本无法从最初提供该页面的服务器请求资源,除非服务器允许所有外部请求,或明确地将您的域列入白名单。
因此,您可以从服务器端执行此操作,但不能从客户端执行此操作,除非
Access-Control-Allow-Origin
标题*
(允许所有人)或列入白名单的列表,或答案 1 :(得分:0)
首先要做的是将错误回调添加到AJAX函数中。您需要阅读包含错误的响应。 http://api.jquery.com/jQuery.ajax/
我怀疑您会发现,出于安全考虑,您仅限于域名。仍有希望,它被称为CORS。
http://techblog.constantcontact.com/software-development/using-cors-for-cross-domain-ajax-requests/
还要注意变量&#34; crossDomain&#34;在ajax函数中。必须将其设置为true才能启用CORS。由于时间问题,某些场景需要jsonpcallback。
$.ajax({
type: "POST",
url: url,
data: payload,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
alert(data);
},
error: function ( jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
// alert(errorThrown);
}
});
除非您确定该网站允许跨域连接,这种情况很少见,否则您可能会失败。如果它在您的函数中设置JSONP(与JSON非常不同),那么您是否知道要传回的回调函数?更仔细地回顾一下jQuery API。对于这种类型的连接,您必须了解很多细节。