是否可以在JSON中更改页面webmethod响应,删除.d节点?

Jos*_*tos 8 vb.net asp.net jquery json web-services

我知道我可以通过ASHX处理程序实现这一点,但我真的需要从页面webmethod.

我正在使用以下代码在页面javascript中调用页面webmethod:

        $.ajax({ type: 'POST', url: '<%= ResolveUrl("~/teste-datatables.aspx/getdata") %>',data: '{ a: ' + id + '}', contentType: 'application/json; charset=utf-8', dataType: 'json',
                success: function (response) {
                        console.log( response);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        console.log('textStatus:' + textStatus);
                        console.log('errorThrown:' + errorThrown);
                        console.log(XMLHttpRequest);
                    }
            });
Run Code Online (Sandbox Code Playgroud)

我有一个JSON文件teste.json(只是为了保持数据库交互并促进你们的测试):

{
  "draw": 1,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    [
      "Airi",
      "Satou",
      "Accountant",
      "Tokyo",
      "28th Nov 08",
      "$162,700"
    ],
    [
      "Angelica",
      "Ramos",
      "Chief Executive Officer (CEO)",
      "London",
      "9th Oct 09",
      "$1,200,000"
    ],
    [
      "Ashton",
      "Cox",
      "Junior Technical Author",
      "San Francisco",
      "12th Jan 09",
      "$86,000"
    ],
    [
      "Bradley",
      "Greer",
      "Software Engineer",
      "London",
      "13th Oct 12",
      "$132,000"
    ],
    [
      "Brenden",
      "Wagner",
      "Software Engineer",
      "San Francisco",
      "7th Jun 11",
      "$206,850"
    ],
    [
      "Brielle",
      "Williamson",
      "Integration Specialist",
      "New York",
      "2nd Dec 12",
      "$372,000"
    ],
    [
      "Bruno",
      "Nash",
      "Software Engineer",
      "London",
      "3rd May 11",
      "$163,500"
    ],
    [
      "Caesar",
      "Vance",
      "Pre-Sales Support",
      "New York",
      "12th Dec 11",
      "$106,450"
    ],
    [
      "Cara",
      "Stevens",
      "Sales Assistant",
      "New York",
      "6th Dec 11",
      "$145,600"
    ],
    [
      "Cedric",
      "Kelly",
      "Senior Javascript Developer",
      "Edinburgh",
      "29th Mar 12",
      "$433,060"
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)

并尝试了webmethod中的几种变体......

Test1将 JSON从文件加载到字符串,然后返回它

<System.Web.Script.Services.ScriptMethod(ResponseFormat:=ResponseFormat.Json), System.Web.Services.WebMethod(True)>
Public Shared Function getdata(a As Integer) As String
    Dim path As String = HttpContext.Current.Server.MapPath("/teste.json")
    Dim jsonString As String = File.ReadAllText(path)
    Return jsonString.Replace(vbCr, "").Replace(vbLf, "")
End Function
Run Code Online (Sandbox Code Playgroud)

结果是:

{d: "{  "draw": 1,  "recordsTotal": 57,  "recordsFilter ... gh",      "29th Mar 12",      "$433,060"    ]  ]}"}
Run Code Online (Sandbox Code Playgroud)

Test2将 JSON从文件加载到字符串,将其转换为datablesnet对象,然后实现它并写入当前上下文

<System.Web.Script.Services.ScriptMethod(ResponseFormat:=ResponseFormat.Json), System.Web.Services.WebMethod(True)>
Public Shared Sub getdata6(a As Integer)
    Dim path As String = HttpContext.Current.Server.MapPath("/teste.json")
    Dim jsonString As String = File.ReadAllText(path)
    Dim mytable As datatablesnet = Newtonsoft.Json.JsonConvert.DeserializeObject(Of datatablesnet)(jsonString)
    Dim serializer As New JavaScriptSerializer
    HttpContext.Current.Response.ContentType = "application/json"
    HttpContext.Current.Response.Write(serializer.Serialize(mytable))
End Sub
Run Code Online (Sandbox Code Playgroud)

我得到一个错误并分析响应,我发现它是(最后添加{"d":null}:

{"draw":1,"recordsTotal":57,"recordsFiltered":57,"data":[["Airi","Satou","Accountant","Tokyo","28th Nov 08","$162,700"],["Angelica","Ramos","Chief Executive Officer (CEO)","London","9th Oct 09","$1,200,000"],["Ashton","Cox","Junior Technical Author","San Francisco","12th Jan 09","$86,000"],["Bradley","Greer","Software Engineer","London","13th Oct 12","$132,000"],["Brenden","Wagner","Software Engineer","San Francisco","7th Jun 11","$206,850"],["Brielle","Williamson","Integration Specialist","New York","2nd Dec 12","$372,000"],["Bruno","Nash","Software Engineer","London","3rd May 11","$163,500"],["Caesar","Vance","Pre-Sales Support","New York","12th Dec 11","$106,450"],["Cara","Stevens","Sales Assistant","New York","6th Dec 11","$145,600"],["Cedric","Kelly","Senior Javascript Developer","Edinburgh","29th Mar 12","$433,060"]]}{"d":null}
Run Code Online (Sandbox Code Playgroud)

Test3将 JSON从文件加载到字符串,将其转换为datablesnet对象,然后实现并返回它

<System.Web.Script.Services.ScriptMethod(ResponseFormat:=ResponseFormat.Json), System.Web.Services.WebMethod(True)>
Public Shared Function getdata5(a As Integer) As String
    Dim path As String = HttpContext.Current.Server.MapPath("/teste.json")
    Dim jsonString As String = File.ReadAllText(path)
    Dim mytable As datatablesnet = Newtonsoft.Json.JsonConvert.DeserializeObject(Of datatablesnet)(jsonString)
    Dim serializer As New JavaScriptSerializer

    Return serializer.Serialize(mytable)
End Function
Run Code Online (Sandbox Code Playgroud)

Test1的结果是一样的:

{d: "{  "draw": 1,  "recordsTotal": 57,  "recordsFilter ... gh",      "29th Mar 12",      "$433,060"    ]  ]}"}
Run Code Online (Sandbox Code Playgroud)

我真的需要摆脱.d节点,直接从响应而不是响应d接收JSON .有什么方法可以从页面webmethod实现这一点吗?

Rez*_*aei 4

我真的需要摆脱.d节点,直接从响应而不是从response.d. 有什么方法可以从页面实现此目的WebMethod吗?

就在这里。可以直接将结果写入response:

<System.Web.Services.WebMethod(True)>
Public Shared Sub getdata(a As Integer)
    Dim path As String = HttpContext.Current.Server.MapPath("/teste.json")
    Dim jsonString As String = System.IO.File.ReadAllText(path)
    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.ContentType = "application/json; charset=utf-8"
    HttpContext.Current.Response.Write(jsonString)
    HttpContext.Current.Response.Flush()
    HttpContext.Current.Response.End()
End Sub
Run Code Online (Sandbox Code Playgroud)

如果您需要在代码中的多个类中执行此操作,您可以轻松地Sub WriteJsonToResponse(obj as Object)在方法主体中创建共享的 and ,首先使用orobj将其序列化为 json ,然后像上面的方法一样将其写入响应。JavaScriptSerializerNewtonsoft.JsonConvert

  • 题外话,但您也可以切换到 Web API 并在您的站点中与 Web 表单并排托管 Web API。 (2认同)