我将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>
点击按钮后
答案 0 :(得分:1)
取消注释.asmx&amp;中的以下行。它会起作用。
// [System.Web.Script.Services.ScriptService]
答案 1 :(得分:0)
将以下代码放在global.asax文件中,并在&#34; Application_BeginRequest&#34;
中调用此方法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();
}
}