9

在过去的 3 个小时里,我一直在寻找 100 个链接,例如将 scriptfactory 添加到 webconfig、3 个错误、设置内容类型等。

我无法弄清楚实际上是什么错误。

环境:在 .net 4.0 上运行的服务 在 .net 4.0 上运行的 Web 应用程序

要求:我需要将 jqGrid 与 asmx Web 服务绑定,该服务将 json 作为字符串返回给我。 Web 服务文件包含以下代码。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class SampleService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetJsonServerProcess()
    {
        int memory = 1;
        string json = string.Empty;
        var obj = (System.Diagnostics.Process.GetProcesses().Where(r => r.WorkingSet64 > memory).Select(p => new { p.ProcessName, p.WorkingSet64 }).ToArray());
        json = Lib.ToJSON(obj);
        return json;
    }
}

Javascript如下

<script type="text/javascript">
    $(document).ready(function () {
        jQuery("#jqgajax").jqGrid({
            ajaxGridOptions: { type: "POST", contentType: 'application/json; charset=utf-8'  },
            url:'http://localhost:1092/SampleService.asmx/GetJsonServerProcess',
            datatype: "json",
            data: "{}",
            colNames: ['ProcessName', 'WorkingSet64'],
            colModel: [
                        { name: 'ProcessName', index: 'ProcessName', width: 55 },
                        { name: 'WorkingSet64', index: 'WorkingSet64', width: 90 }
                    ],
            rowNum: 10,
            width: 700,
            rowList: [10, 20, 30],
            sortname: 'invdate',
            viewrecords: true,
            sortorder: "desc",
            caption: "New API Example"
        });
    });
</script>

HTML如下

<table id="jqgajax">
</table>
<div id="jqgajax">
</div>

单击调用按钮时的 Web 服务输出

<string xmlns="http://tempuri.org/">
[{"ProcessName":"Dropbox","WorkingSet64":22736896},
 {"ProcessName":"fdhost","WorkingSet64":1941504},
 {"ProcessName":"IntelliTrace","WorkingSet64":39276544}
]
</string>

请建议我缺少什么。 <string xmlns="http://tempuri.org/">标签激怒了我。我假设这些标签不会让我的网格能够绑定。

更新:

ASMX 服务现在如下所示。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class SampleService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<demo> GetJsonServerProcess()
    {
        List<demo> test = new List<demo>();

        for(int i=1;i<=10;i++)
            test.Add(new demo { ProcessName = string.Format("Sample {0}",i), WorkingSet64 = i });

        var re = test;
        return re;
    }
}

public class demo
{
    public string ProcessName { get; set; }
    public int WorkingSet64 { get; set; }
}
4

8 回答 8

7

单击 Invoke 按钮将返回 XML,因为请求未指定contentType: 'application/json; charset=utf-8'. 因此,单击 Invoke 按钮的实验并没有真正的帮助。

您的代码中的主要问题是您将数据转换为 web 方法内的字符串。线

json = Lib.ToJSON(obj);

不需要。通常做的是返回对象。GetJsonServerProcess应该更改为类似

[ScriptService]
public class SampleService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<Process> GetJsonServerProcess()
    {
        int memory = 1;
        return System.Diagnostics.Process.GetProcesses()
                   .Where(r => r.WorkingSet64 > memory)
                   .Select(p => new { p.ProcessName, p.WorkingSet64 })
                   .ToList();
    }
}

下一个问题是等待 jqGrid 的默认输入格式是另一种(参见此处)。因此,您需要指定jsonReader哪些描述数据格式。在您的情况下,它将类似于

jsonReader: {
    repeatitems: false,
    id: "ProcessName",
    root: function (obj) { return obj; },
    page: function () { return 1; },
    total: function () { return 1; },
    records: function (obj) { return obj.length; }
}

此外,您永远不应该http://localhost:1092/在 Ajax 中使用前缀,url因为出于安全原因,您只能从同一站点获取数据。datajqGrid 中的参数与 jQuery 中的参数有另一个含义,因此您应该删除data: "{}"type: "POST"ajaxGridOptionsto移动mtype: "POST"。结果你会有类似的东西

$(document).ready(function () {
    $("#jqgajax").jqGrid({
        mtype: "POST",
        ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
        url: '/SampleService.asmx/GetJsonServerProcess',
        postData: "{}", // remove all parameters which jqGrid send typically
        datatype: "json",
        colNames: ['ProcessName', 'WorkingSet64'],
        colModel: [
            { name: 'ProcessName', index: 'ProcessName', width: 155 },
            { name: 'WorkingSet64', index: 'WorkingSet64', width: 190 }
        ],
        jsonReader: {
            repeatitems: false,
            id: "ProcessName",
            root: function (obj) { return obj; },
            page: function () { return 1; },
            total: function () { return 1; },
            records: function (obj) { return obj.length; }
        },
        rowNum: 10,
        loadonce: true,
        gridview: true,
        height: 'auto',
        rowList: [10, 20, 30],
        viewrecords: true,
        sortorder: "desc",
        caption: "New API Example"
    });
});

我没有测试代码,但它应该更接近您的需要。

更新:您应该通过更改来修复代码jsonReader您可以在此处下载工作演示。它显示网格

在此处输入图像描述

我在服务器端使用了代码

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Services;

namespace jqGridWebASMX
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class SampleService : WebService
    {
        [WebMethod]
        public List<Demo> GetJsonServerProcess()
        {
            const int memory = 1;
            return Process.GetProcesses()
                .Where (r => r.WorkingSet64 > memory)
                .Select(p => new Demo {
                    Id = p.Id,
                    ProcessName = p.ProcessName,
                    WorkingSet64 = p.WorkingSet64
                })
                .ToList();
        }
    }

    public class Demo
    {
        public int Id { get; set; }
        public string ProcessName { get; set; }
        public long WorkingSet64 { get; set; }
    }
}

在客户端

$("#list").jqGrid({
    mtype: "POST",
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    url: '/SampleService.asmx/GetJsonServerProcess',
    postData: "{}", // remove all parameters which jqGrid send typically
    datatype: "json",
    colNames: ['ProcessName', 'WorkingSet64'],
    colModel: [
        { name: 'ProcessName', index: 'ProcessName', width: 200 },
        { name: 'WorkingSet64', index: 'WorkingSet64', width: 120,
            formatter: 'integer', sorttype: 'int', align: 'right' }
    ],
    jsonReader: {
        repeatitems: false,
        id: "Id",
        root: function (obj) { return obj.d; },
        page: function () { return 1; },
        total: function () { return 1; },
        records: function (obj) { return obj.d.length; }
    },
    rowNum: 10,
    loadonce: true,
    gridview: true,
    height: 'auto',
    pager: '#pager',
    rowList: [10, 20, 30],
    rownumbers: true,
    viewrecords: true,
    sortorder: "desc",
    caption: "New API Example"
});
$("#pager_left").hide(); // hide unused part of the pager to have more space
于 2012-05-30T22:01:49.737 回答
1

好的,我遇到了同样的错误,经过大量试验和错误,这是我的“快速而肮脏”的解决方案;

$.get(url, {var1: parameter1, var2: parameter2}, function(data){
    data = JSON.parse($(data).find("string").text());
    alert("data.source: " + data.source);
});
于 2013-08-13T10:08:02.463 回答
1

此代码完美运行

SqlDataAdapter sda = new SqlDataAdapter(strsql, ConfigurationManager.ConnectionStrings["BTConString"].ToString());
DataSet das = new DataSet();
sda.Fill(das);
Context.Response.Output.Write(JsonConvert.SerializeObject(das, Newtonsoft.Json.Formatting.Indented));
Context.Response.End();

return string.Empty;
于 2017-06-21T07:16:36.697 回答
1

以下代码应该可以解决问题:

this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(json);
于 2016-07-01T13:58:36.547 回答
0
  response = await client.GetAsync(RequestUrl, HttpCompletionOption.ResponseContentRead);
                if (response.IsSuccessStatusCode)
                {
                    _data = await response.Content.ReadAsStringAsync();
                    try
                    {
                        XmlDocument _doc = new XmlDocument();
                        _doc.LoadXml(_data);
                        return Request.CreateResponse(HttpStatusCode.OK, JObject.Parse(_doc.InnerText));
                    }
                    catch (Exception jex)
                    {
                        return Request.CreateResponse(HttpStatusCode.BadRequest, jex.Message);
                    }
                }
                else
                    return Task.FromResult<HttpResponseMessage>(Request.CreateResponse(HttpStatusCode.NotFound)).Result;
于 2015-05-17T10:19:57.470 回答
0

在功能开始之前把下面

[System.Web.Services.WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

使功能无效

当函数结束时放在下面的行

this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(json);

示例程序

        [System.Web.Services.WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void testJson()
        {
            string json = "{}";
            this.Context.Response.ContentType = "";
            this.Context.Response.Write(json);
        }
于 2019-05-07T06:42:37.293 回答
0

您可以将您的网址放在邮递员中并使用响应

像这样我正在使用php

<?php

$curl = curl_init();

curl_setopt_array($curl, array( CURLOPT_URL => 'your url', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', ));

$response = curl_exec($curl);

curl_close($curl); echo $response;

?>
于 2020-12-05T07:12:17.280 回答
-1

对于有效的 JSON 响应,请使用此代码..

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class SampleService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void GetJsonServerProcess()
    {
        int memory = 1;
        string json = string.Empty;
        var obj = (System.Diagnostics.Process.GetProcesses().Where(r => r.WorkingSet64 > memory).Select(p => new { p.ProcessName, p.WorkingSet64 }).ToArray());
        json = Lib.ToJSON(obj);
       this.Context.Response.ContentType = "application/json; charset=utf-8";
            this.Context.Response.Write(json);

    }
}
于 2015-07-18T10:55:45.917 回答