jQuery jqGrid 与 Ajax 数据 (JSON):使用 azure 数据库中的“url”参数在网格中加载数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15866383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:55:48  来源:igfitidea点击:

jqGrid with Ajax data (JSON) : load data in grid using "url" parameter from azure database

jqueryazurejqgridjqgrid-inlinenav

提问by Mohit

I have one doubt with ajax implementation. I could find that "url" parameter need to be defined as "service_name1.azure-mobile.net/tables/" to fetch data to populate grid. But I need to add request header "X-ZUMO-APPLICATION" to define application key. To accomplish this, I think I have to make a httprequest with proper headers in a function and need to set reference of that function in some parameter of jqGrid to load data. Can you point out how is it possible to achieve?

我对 ajax 实现有一个疑问。我发现需要将“url”参数定义为“service_name1.azure-mobile.net/tables/”以获取数据以填充网格。但是我需要添加请求头“X-ZUMO-APPLICATION”来定义应用程序密钥。为了实现这一点,我想我必须在函数中使用适当的标头创建一个 httprequest,并且需要在 jqGrid 的某些参数中设置该函数的引用以加载数据。你能指出如何实现吗?

Page on which jqGrid is used, starts with "https://service_name2.azure-mobile.net"

使用 jqGrid 的页面,以“ https://service_name2.azure-mobile.net”开头

Here service_name1 is azure mobile service name and service_name2 is azure web service name and I have enabled CORS (cross object resource sharing) for service_name2 on mobile service service_name1.

此处 service_name1 是 azure 移动服务名称,service_name2 是 azure Web 服务名称,我在移动服务 service_name1 上为 service_name2 启用了 CORS(跨对象资源共享)。

Please let me know if any additional information is required

如果需要任何其他信息,请告诉我

Updated code to make it work with Ajax call :

更新代码以使其与 Ajax 调用一起使用:

        jQuery("#list4").jqGrid({
        datatype: "json",
        url : 'https://mohit.azure-mobile.net/tables/Schedules',
        height: "auto",
        colNames: ['RowNo', 'RouteId', 'Area],
        colModel: [
                  { name: 'id', index: 'id', width: 50, sortable: false },
                  { name: 'RouteId', index: 'RouteId', width: 50, sortable: false, editable: true, editrules: { required: true} },
                  { name: 'Area', index: 'Area', width: 130, sortable: false, editable: true, editrules: { required: true} },
              ],
        rowList: [10, 20, 30],
        loadBeforeSend: function(jqXHR) {
                                            jqXHR.setRequestHeader('X-ZUMO-APPLICATION', 'mykey');
                                        },
        ajaxGridOptions: { contentType: "application/json" },
        postData: "",
        serializeGridData: function (data) {return JSON.stringify(data);},
        pager: '#pager1',
        viewrecords: true,
        caption: "Schedule Data",
        //loadonce: true,
        gridview: true
    });

Weird thing is, I am not able to capture this request using fiddler so I am capturing request using IE developer toolbar (using F12). I tried composing a request using fiddler, used GET with url'https://mohit.azure.net/tables/Schedules' and set header parameter as X-ZUMO-APPLICATION : appKey. I got proper response (expected JSON formatted table data) with this request. So I am feeling appended parameters are issue.

奇怪的是,我无法使用 fiddler 捕获此请求,因此我使用 IE 开发人员工具栏(使用 F12)捕获请求。我尝试使用 fiddler 编写请求,使用带有 url' https://mohit.azure.net/tables/Schedules' 的GET并将标头参数设置为 X-ZUMO-APPLICATION : appKey。我对这个请求得到了正确的响应(预期的 JSON 格式的表数据)。所以我觉得附加参数有问题。

Update code part 2

更新代码第 2 部分

    jQuery("#list4").jqGrid({
        datatype: "json",
        url : 'https://mohit.azure-mobile.net/tables/Schedules',
        height: "auto",
        colNames: ['RowNo', 'RouteId', 'Area'],
        colModel: [
                  { name: 'id', index: 'id', width: 50, sortable: false },
                  { name: 'RouteId', index: 'RouteId', width: 50, sortable: false, editable: true, editrules: { required: true} },
                  { name: 'Area', index: 'Area', width: 130, sortable: false, editable: true, editrules: { required: true} }
              ],
        rowList: [10, 20, 30],
        loadBeforeSend: function(jqXHR) {
                                            jqXHR.setRequestHeader('X-ZUMO-APPLICATION', 'myKey');
                                        },
        loadComplete: function () {
                                        //alert("OK");
                                  },
        loadError: function (jqXHR, textStatus, errorThrown) {
                                                                    alert('HTTP status code: ' + jqXHR.status + '\n' +
                                                                    'textStatus: ' + textStatus + '\n' +
                                                                    'errorThrown: ' + errorThrown);
                                                                     alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
                                                             },
        ajaxGridOptions: { contentType: "application/json", cache: true },
        postData: "",
        pager: '#pager1',
        viewrecords: true,
        caption: "Schedule Data",
        loadonce: true,
        gridview: true
    });

   var inlineparams = {
        restoreAfterSelect: false,
        add: true,
        edit: true,
        save: true,
        cancel: true,
        del: true
    };

    jQuery("#list4").jqGrid('navGrid', "#pager1", { edit: false, save: false, add: false, cancel: false, del: false });
    jQuery("#list4").jqGrid('inlineNav', "#pager1", inlineparams);       
}

Solution for loading data in grid with jqGrid version 4.4.5 using Ajax way

jqGrid 4.4.5版用ajax方式加载grid中数据的解决方案

                       jQuery("#list4").jqGrid({
        datatype: "json",
        url : 'https://mohit.azure-mobile.net/tables/Schedules',
        height: "auto",
        colNames: ['RowNo', 'RouteId', 'Area'],
        colModel: [
                  { name: 'id', index: 'id', width: 50, sortable: false },
                  { name: 'RouteId', index: 'RouteId', width: 50, sortable: false, editable: true, editrules: { required: true} },
                  { name: 'Area', index: 'Area', width: 130, sortable: false, editable: true, editrules: { required: true} },
              ],
        rowList: [10, 20, 30],
        loadBeforeSend: function(jqXHR) {
                                            jqXHR.setRequestHeader('X-ZUMO-APPLICATION', 'myKey');
                                        },
        loadComplete: function () {
                                        //alert("OK");
                                  },
        loadError: function (jqXHR, textStatus, errorThrown) {
                                                                    alert('HTTP status code: ' + jqXHR.status + '\n' +
                                                                    'textStatus: ' + textStatus + '\n' +
                                                                    'errorThrown: ' + errorThrown);
                                                                     alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
                                                             },
        ajaxGridOptions: { contentType: "application/json", cache: true },
        postData: "",
        pager: '#pager1',
        viewrecords: true,
        caption: "Schedule Data",
        loadonce: true,
        jsonReader: {repeatitems: false},
        gridview: true
    });

采纳答案by Oleg

First of all I think the the title of the question "how to call custom function to load data instead of using “url” parameter" is incorrect. I think that what you describe could be implemented per standard Ajax call, but using JSONP type instead of JSON.

首先我认为“如何调用自定义函数加载数据而不是使用“url”参数”这个问题的标题是不正确的。我认为您描述的内容可以按标准 Ajax 调用实现,但使用 JSONP 类型而不是 JSON。

To set custom HTTP/HTTPS headers you can use setRequestHeadermethod of inside of loadBeforeSendcallback of jqGrid. See the answer. In case of editing of grid inside of beforeSendcallback of jQuery.ajax call which do jqGrid. You can use ajaxEditOptionsor ajaxRowOptionsoption of jqGrid (depend on editing mode which you use) to set the beforeSendcallback of jQuery.ajax call. Alternatively you can use headersoption of jQuery.ajax (one can set it in jqGrid using ajaxGridOptions, ajaxEditOptionsor ajaxRowOptions).

要设置自定义 HTTP/HTTPS 标头,您可以使用jqGridsetRequestHeader的内部loadBeforeSend回调方法。见答案。如果在beforeSend执行 jqGrid 的 jQuery.ajax 调用的回调中编辑网格。您可以使用jqGrid 的ajaxEditOptionsajaxRowOptions选项(取决于您使用的编辑模式)来设置beforeSendjQuery.ajax 调用的回调。或者,您可以使用headersjQuery.ajax 选项(可以使用ajaxGridOptions,ajaxEditOptions或将其设置在 jqGrid 中ajaxRowOptions)。

I think that if you configured correctly Cross-Origin Resource Sharing (CORS) (see here) you could use JSONP in jqGrid to load the data. See examples here, hereand here.

我认为,如果您正确配置了跨域资源共享 (CORS)(请参阅此处),您可以在 jqGrid 中使用 JSONP 来加载数据。请参阅此处此处此处的示例。

UPDATED: I can't test the code, but I think you should change some options/callbacks which you use:

更新:我无法测试代码,但我认为您应该更改您使用的一些选项/回调:

  1. remove serializeGridDatais you use postData: ""
  2. change datatype: "json"to datatype: "jsonp"
  3. change ajaxGridOptions: { contentType: "application/json" }to ajaxGridOptions: { contentType: "application/json", cache: true }
  1. 删除serializeGridData你使用postData: ""
  2. 更改datatype: "json"datatype: "jsonp"
  3. 更改ajaxGridOptions: { contentType: "application/json" }ajaxGridOptions: { contentType: "application/json", cache: true }

If it will not help I would recommend you to use tools like Fiddlerto trace HTTPS traffic. You will need additionally activate tracing of HTTPS inside the tool (see the documentation).

如果它没有帮助,我建议您使用Fiddler 之类的工具来跟踪 HTTPS 流量。您还需要在工具内激活 HTTPS 跟踪(请参阅文档)。

UPDATED 2: It seems that in case of usage Windows Azure Mobile Services you can use datatype: "json"and url: 'https://<service_name1>.azure-mobile.net/tables/<TableName>'. To get the data it's important only to use

更新 2:似乎在使用 Windows Azure 移动服务的情况下,您可以使用datatype: "json"url: 'https://<service_name1>.azure-mobile.net/tables/<TableName>'。要获取数据,重要的是只使用

ajaxGridOptions: { contentType: "application/json" },
postData: "",
jsonReader: {
    repeatitems: false,
    root: function (obj) {
        return obj;
    }
}

To be able to modify the data with respect of inline editing you should produce HTTP request having

为了能够在内联编辑方面修改数据,您应该生成具有以下内容的 HTTP 请求

PATCH https://mstrans.azure-mobile.net/tables/<TableName>/<TableItemId> HTTP/1.1
Content-Type: application/json

in the HTTP header and JSON data with the modified row, but without unneeded operparameter. To do this you can

在带有修改行的 HTTP 标头和 JSON 数据中,但没有不需要的oper参数。要做到这一点,你可以

editurl: "https://mohit.azure-mobile.net/tables/Schedules",
ajaxRowOptions: { contentType: "application/json" },
serializeRowData: function (postData) {
    if (postData != null && postData.oper) {
        delete postData.oper;
    }
    return JSON.stringify(postData);
}

The code above will do almost all what one need with the exception that it will be used as URL "https://mohit.azure-mobile.net/tables/" instead of "https://mohit.azure-mobile.net/tables//".

上面的代码几乎可以做所有需要的事情,除了它将用作 URL " https://mohit.azure-mobile.net/tables/" 而不是 " https://mohit.azure-mobile.net /表//”。

To make the last step one can modify urlinside of for example oneditfunccallback of inlineparamsor better jqGridInlineEditRowevent:

要进行最后一步,可以url在例如oneditfunc回调inlineparams或更好的jqGridInlineEditRow事件内部进行修改:

var inlineparams = {
    editParams: { mtype: "PATCH", keys: true},
    addParams: {
        addRowParams: { mtype: "POST", keys: true }
    }
};

jQuery("#list4").bind("jqGridInlineEditRow", function (e, rowid, options) {
    if (options.mtype === "PATCH") {
        options.url = "https://mohit.azure-mobile.net/tables/Schedules/" +
            encodeURIComponent(rowid);
    }
});