我的网络服务代码是
[WebMethod]
public List<test> GetMachineData_List(string prefix, int person_id)
{
using (var db = new TestDB())
{
List<test> list = db.Fetch<test>("select id,name from machine_data_collection mc where mc.id=@0 and name like '%" + prefix + "%'", person_id);
return list.ToList();
}
}
我的 jquery Ajax 调用是
$("#textbx").autocomplete(
{
source: function (request, response) {
$.ajax({
url: 'http://localhost:4787/ws/webservice.asmx/GetMachineData_List',
data: { prefix: request.term.toString() ,person_id:1},
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var jsonArray;
try {
jsonArray = $.parseJSON(data.d); // using jQuery
} catch (e) {
jsonArray = data.d; // using jQuery
}
response($.map(jsonArray, function (item) {
return {
id: item.id,
value: item.Name
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var msg = XMLHttpRequest.responseJSON.d;
if (msg == undefined) {
alert( "Something went wrong !!" + errorThrown);
} else {
alert( "Error"+ msg);
}
}
});
},
minLength: 2,
select: function (event, ui) {
var idControl = this.dataset.bindcontrol;
try {
alert(ui.item.id);
}
catch (ex) {
alert( "Oops .. Something happend unexpected !! .. Please redo ");
}
}
}
);
我在 web.config 代码中启用跨源是
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:21702/" />
<add name="Access-Control-Allow-Headers" value="X-AspNet-Version,X-Powered-By,Date,Server,Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Content-Length,Content-Type,Host,Origin,Pragma,Referer,User-Agent" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
<add name="Access-Control-Max-Age" value="1000" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
更改文本框中的文本时发生错误。
Ajax 调用的错误消息是:
XMLHttpRequest 无法加载http://localhost:4787/ws/webservice.asmx/GetMachineData_List http://localhost:4787/ws/webservice.asmx/GetMachineData_List。回复
预检请求未通过访问控制检查:否
请求中存在“Access-Control-Allow-Origin”标头
资源。起源 'http://本地主机:21702 http://localhost:21702' 因此不允许
使用权。响应的 HTTP 状态代码为 500。