[英]JQuery AJAX throws no error but doesn't work as well
我有这个JQuery AJAX代码,它使用签名调用ASP.NET Web Service方法:“public bool ValidateUser(string username,string password)”它应该返回true / false。 AJAX不会抛出任何错误,但也无法正常工作。
<script>
$('#btn').click(function () {
var a=$('#name').val(), b=$('#pass').val();
$.ajax({
url:'http://localhost:22664/StockServices.asmx/ValidateUser',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ username: a, password: b }),
dataType: "json",
method: 'post',
success: function (data) {
alert("Msg: " + data.d);
}, error: function (err) { alert("failed");
console.log(err); }
});
});
</script>
要启用从javascript调用.asmx
服务,您需要将此属性添加到.asmx
服务定义:
[System.Web.Script.Services.ScriptService]
因此,您的完整服务可能如下所示:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class StockServices : System.Web.Services.WebService
{
[WebMethod]
public bool ValidateUser(string username,string password)
{
System.Diagnostics.Debugger.Break();
return true;
}
}
还要小心使用url:'http://localhost:22664/StockServices.asmx/ValidateUser'
因为当此代码部署到生产时它将不再有效。您可能希望将其更改为:
url: 'StockServices.asmx/ValidateUser'
我注意到在你的ajax调用中,你正在使用:
$.ajax({
...
method: 'post',
...
});
你应该试试:
$.ajax({
...
type: 'post',
...
});
我在此链接中找到了以下代码段
类型(默认:'GET')
类型:String方法的别名。 如果您使用的是1.9.0之前的jQuery版本,则应该使用type。
可能是你使用旧版本的jQuery不接受method
但接受type
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.