我正在尝试编写一个 jQuery AJAX 调用将使用的 ASP.net Web 服务。我完全无计可施,试图让它发挥作用。我在网上看到了许多类似的问题,但我一直无法找到适合的解决方案。
当我尝试进行 ajax 调用(通过 jquery)时,我从服务器获得了成功的响应,但由于解析器错误,请求失败。
我已经验证了 web 服务返回的 json 并且它是有效的。这个问题似乎源于 asp.net 将 json 对象作为 xml 返回的事实。
我已经将返回类型指定为 json 使用
<Script.Services.ScriptMethod(responseFormat:=Script.Services.ResponseFormat.Json)> _
我添加了以下 http 处理程序,因为它被提及为潜在的修复
<httpHandlers>
    <remove verb="*" path="*.asmx" />
    <add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false" />
</httpHandlers>
在我的 jquery ajax 设置中,内容类型设置为“application/json; charset=utf-8”,数据类型设置为“json”。请求类型似乎是正确的,但响应始终是 xml。
我可以通过删除 dataType 成功发出请求,但我非常想避免使用 eval 反序列化数据。
如果有人有任何建议,我将不胜感激。这几天我一直在拔头发。
JAVASCRIPT
(function($) {
  $.ajaxSetup({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    global: false,
    dataType: "json"
  });
  function auto() {
    console.log("test");
    return;
  };
  $.fn.species = {
    test: function() {
      alert("test");
    },
    load: function() { //load and attach species list to element as dropdown
      $.ajax({
        url: "SpeciesService.asmx/List",
        success: function(msg) {
          console.log(msg);
        },
        error: function(xhr, desc, exceptionobj) {
          console.log(xhr.responseText);
          console.log(desc);
          console.log(exceptionobj);
        }
      });
      return this;
    }
  }; //Species Block
})(jQuery); //jQuery Alias Block
ASP.NET 网络服务
<%@ WebService Language="VB" Class="SpeciesService" %>
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports Species
Imports System.Runtime.Serialization
' 要允许使用 ASP.NET AJAX 从脚本调用此 Web 服务,请取消注释以下行。'_
_ _ 公共类物种服务
Inherits System.Web.Services.WebService
<WebMethod()> _
<Script.Services.ScriptMethod(responseFormat:=Script.Services.ResponseFormat.Json)> _
Public Function Data(ByVal id As Integer) As String
    Dim curSpecies As New Species(id)
    Return curSpecies.serialize
End Function
<WebMethod()> _
<Script.Services.ScriptMethod(responseFormat:=Script.Services.ResponseFormat.Json)> _
Public Function List() As String
    Return Species.list()
End Function
结束类