[英]jQuery ajax not connect web service .net (asmx)
我將javascript ajax連接到webservice asmx,但無法正常工作。 我測試了從aspx連接到webservice的工作。
的HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('#btnCallService').click(function () {
$.ajax({
type: 'POST',
url: 'http://xxxxxxxx/ws/webservice.asmx/HelloWorld',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblData').html(JSON.stringify(response));
},
error: function (error) {
console.log(error);
}
});
});
});
</script>
</head>
<body>
<input type="button" id="btnCallService" value="GetEmployeeDetail" />
<label id="lblData"></label>
</body>
</html>
單擊按鈕后
只需在.asmx中取消注釋下面的行即可。
// [System.Web.Script.Services.ScriptService]
將以下代碼放入global.asax文件中,然后在“ Application_BeginRequest”中調用此方法
static void EnableCrossDomain()
{
string origin = HttpContext.Current.Request.Headers["Origin"];
if (string.IsNullOrEmpty(origin)) return;
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
string method = HttpContext.Current.Request.Headers["Access-Control-Request-Method"];
if (!string.IsNullOrEmpty(method))
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", method);
string headers = HttpContext.Current.Request.Headers["Access-Control-Request-Headers"];
if (!string.IsNullOrEmpty(headers))
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", headers);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = 204;
HttpContext.Current.Response.End();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.