我通过jQuery调用一个支持AJAX的asmx web服务托管在远程ASP.Net网站上。
jQuery位于我的localhost ASP.Net网站上托管的页面上。
问题是,当进行上述调用时,jQuery显示错误(即触发错误回调),即使我在Fiddler中检查响应时,没有错误,但是来自Web服务的正确预期值。正确的返回值是'true',正如Fiddler所见,它返回。 我无法弄清楚我在跨域调用中缺少的内容。
jQuery代码,以调用跨域asmx服务
var userName = 'mike';
var password = 'abcd';
var serviceurl = "http://www.kandoodev.com/WebService1.asmx/LoginUser";
$.ajax({
url: serviceurl,
type: 'GET',
crossDomain: true,
contentType: "application/json; charset=utf-8",
data:{ userName: userName, password: password },
dataType: "jsonp",
success: function (msg) {
alert('Cross-Domain Web service call succeeded. We will now call a protected method on the web service. ' + JSON.stringify(msg));
if (msg.toString() === 'true') {
alert('Valid Credentials');
}
else {
alert('Invalid Credentials');
}
},
error: function (error) { alert('ERROR has occurred!'); alert(JSON.stringify(error)) }
});
WebService1.asmx
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the
//following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[PrincipalPermission(SecurityAction.Assert, Unrestricted = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public bool LoginUser(string userName, string password)
{
bool authenticated = false;
if (userName.ToLower() == "mike" && password.ToLower() == "abcd")//you can instead check credentials against a users table in database
{
authenticated = true;
}
return authenticated;
}
}
错误回调中的值如下:
响应小提琴中的TextView如下所示。
<?xml version="1.0" encoding="utf-8"?>
<boolean xmlns="http://tempuri.org/">true</boolean>
答案 0 :(得分:0)
您是否检查过网络服务器的预检请求(即选项请求)是否正在返回标头Access-Control-Allow-Origin:*(或允许的域名)和Access-Control-Allow-Methods:GET,POST(响应中的任何其他动词。因为有些情况下预检请求返回200 OK但错过了CORS标题。