我花了最近5个小时的时间来寻找这个问题,但没有一个解决方案帮助了我,所以这里有:
我有一个返回JSON的asmx webservice
<System.Web.Services.WebMethod()> _
<Script.Services.ScriptMethod(ResponseFormat:=Script.Services.ResponseFormat.Json)> _
Public Function GetObjectsByObjectType(ByVal ObjectType As String)
Dim db As New Database(System.Web.Configuration.WebConfigurationManager.AppSettings("strConnectionStr"))
Return GetJson(DirectCast(db.ExecuteSelect("##queryHere##"), DataSet).Tables(0))
End Function
Public Function GetJson(ByVal dt As DataTable) As String
Return New JavaScriptSerializer().Serialize(From dr As DataRow In dt.Rows Select dt.Columns.Cast(Of DataColumn)().ToDictionary(Function(col) col.ColumnName, Function(col) dr(col)))
End Function
这是托管在服务器上(如果我直接在服务器上使用它可以正常工作)并且我试图从我的localhost测试服务器上访问它
$.ajax({
type: "POST",
url: "http://linkToServer/DatabaseService.asmx/GetObjectsByObjectType",
data: JSON.stringify({ stuff }),
dataType: "json",
timeout: 3000,
contentType: "application/json;charset=utf-8",
xhrFields: {
withCredentials: true
},
success: function (msg) {
console.log(msg);
},
error: function (xhr, ajaxOptions, errorthrown) {
console.log(errorthrown);
}
});
但我总是得到即时超时响应或
XMLHttpRequest无法加载[...]。预检的响应具有无效的HTTP状态代码401
我已经尝试了以下内容:
Access-Control-Allow-Origin "*"
Access-Control-Allow-Credentials "true"
Access-Control-Allow-Headers "Content-Type"
Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
(不确定格式化,但是它们设置正确,我只是不想复制web.config xml的东西)
我找到的唯一可行的解决方案是:
如果我删除
contentType: "application/json;charset=utf-8"
从ajax请求中,我将我的JSON结果包装在XML文档中,我可以解析,但我宁愿直接使用JSON。
所以你知道如何设置,所以我可以获得JSON结果吗?