asp.net - ASP.net JSON Webservice 响应类型的问题

标签 asp.net jquery web-services json asmx

我正在尝试编写一个 ASP.net Web 服务,该服务将由 jQuery AJAX 调用使用。 我完全无计可施,试图让它发挥作用。我在网上看到了很多类似的问题,但一直找不到合适的解决方案。

当我尝试进行 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 Web 服务

<%@ 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 服务,请取消注释以下行。 '_

_ _ 公共(public)类物种服务

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

下课

最佳答案

尝试使用 JQuery 发布虚拟 json 数据,如下所示:

$.ajaxSetup({
    type: "POST",
    data : "{'foo':'bar'}"
...

关于asp.net - ASP.net JSON Webservice 响应类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/712606/

相关文章:

asp.net - 如何使用 ASP.Net -- Html.ActionLink()

android - 访问 asp.net 网络服务

javascript - 使用jquery调用web服务

.net - MSBuild 失败,但在 Visual Studio 中构建工作正常

c# - 跨平台运行 ASP.NET 5

jquery - 如果可能的话,ajax 在提交时进行清理

javascript - 使用 Request.Form 获取禁用的 HTML 复选框的值

javascript - jquery 计算元素

Android httpUrlConnection发送和接收数据

c# - jQuery - 图像管理