前端代码:
为了能在JQ里跨域,需要以上代码放在<system.webServer>和</system.webServer>之间
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery/jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="application/javascript">
$(function () {
var url = "http://www.air.com/test.asmx/UserLogin";
$.ajax({
type: "GET",
url: url,
data: {userName: 'air', userPwd: '123'},
dataType: "html",
success: function (s) {
alert(s)
var jsonstr=s.replace(/<\/?.+?>/g,"");
var json =$.parseJSON(jsonstr);
alert(json.user.id);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(errorThrown);
},
});
})
</script>
</body>
</html>
后端代码:
/// <summary>
/// test 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class test : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=true)]
public string UserLogin(string userName, string userPwd)
{
string returnVal = "";
returnVal = "{\"user\":{\"id\":\"201707031059\",\"name\":\"" + userName + "\",\"pwd\":\"" + userPwd + "\"}}";
return returnVal;
}
}
Web.config:
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
为了能在JQ里调用webservice,需要以上代码放在<system.web>和</system.web>之间
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
为了能在JQ里跨域,需要以上代码放在<system.webServer>和</system.webServer>之间