2013-04-18 174 views
2

我有一個jqGrid發送ajax請求到我的服務器。但是,我的服務器以完全不同的格式發送json響應(我無法更改它)。因此我需要解析來自服務器的響應,所以我的jqGrid可以正確顯示數據。jqGrid - 解析json響應

如果我的理解沒錯,我可以用ajaxGridOptions轉換器。所以,我可以捕捉到答案並解析它。在我看來,轉換器工作正常,並正確解析響應。但是,jqGrid不理解我解析的響應。它永遠顯示一條消息「正在加載...」(我可以在螢火蟲中看到請求/響應正常,控制檯中沒有javascript錯誤)。

有人可以幫我嗎?

這裏是我的代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html><head> 
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/redmond/jquery-ui.css" /> 
    <link rel="stylesheet" type="text/css" href="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/css/ui.jqgrid.css" /> 
</head><body> 

<!-- IMPORT JS --> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script> 
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/js/i18n/grid.locale-en.js"></script> 
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/js/jquery.jqGrid.min.js"></script>  

<script> 

$(document).ready(function() { 
    var parsedResponse = '{"currentPage" : "1", "totalRecords" : 5, "pageSize" : 3,' 
      + '"myData" :[{"id" : "1", "name" : "Name 1" },' 
      + '   { "id" : "3", "name" : "Name 3" },' 
      + '   { "id" : "2", "name" : "Name 2" }]' 
      + '}'; 

    var myGrid = $('<table>').attr("id", "useraccount-search-datagrid"); 
    var myPager = $("<div>").attr("id", "useraccount-search-datagrid-pager"); 

    $("body").append(myGrid, myPager); 

    myGrid.jqGrid({ 
     pager : myPager, 
     // datastr: parsedResponse, // If I use these parameters and remove ajaxGridOptions then it will work fine with the local data 
     // datatype : "jsonstring", // If I use these parameters and remove ajaxGridOptions then it will work fine with the local data 
     serializeGridData : function(data) { 
      return '{"SearchCriteria": {"keyword":"emai","orderByField":"userName","sortOrder":"DESC","pagination":{"pageSize":"10","pageNumber":"2"}}}'; 
     }, 
     ajaxGridOptions: { 
      url: "../rush-controller-testing/userAccount/find", 
      type: "POST", 
      contentType: "application/json; charset=utf-8",   
      dataType: "json", 
      converters: { "text json": function (responseText) { 
        // console.log(responseText); // Shows the response string from the cerver 
        return parsedResponse; 
       } 
      }, 
      success: function(data, textStatus, jqXHR) { 
       // Nice! It shows 'parsedResponse' from 'converters'. Looks good so far. 
       console.log(data); console.log(textStatus); console.log(jqXHR); 
      } 
     }, 
     colModel : [ 
      { name : 'name', index : 'id', width : "500"} 
     ], 
     jsonReader: { 
      root: "myData", page: "currentPage", records: "totalRecords" 
     }, 
     rowNum : 3, 
     viewrecords : true, 
     height : "auto", 
     ignoreCase : true, 
     hidegrid: false 
    }); 

}); 
</script> 
</body> 
</html> 

=== UPDATE ===

我的服務器響應是一樣的東西:

{"UserAccountSearchResult":{ 
    "userAccounts":[{ 
     "userAccountId":18, 
     "clientAccount":{"clientAccountId":19,"name":"name:5791","firstName":"firstName:5791","lastName":"lastName:5791","active":true}, 
     "userName":"[email protected]", 
     "password":"password824504", 
     "firstName":"firstName824504", 
     "lastName":"lastName824504", 
     "isActive":true, 
     "phoneNumbers":{"phoneNumberId":36,"number":824504824504}, 
     "addresses":{"addressId":126,"country":"CANADA","provinceOrState":"ONTARIO","address":"address824504","city":"Windsor","postalCode":"postalCode824504"}, 
     "emails":{"emailId":36,"email":"[email protected]"} 
     },{ 
     "userAccountId":44, 
     "clientAccount":{"clientAccountId":45,"name":"name:3136","firstName":"firstName:3136","lastName":"lastName:3136","active":true}, 
     "userName":"[email protected]", 
     "password":"password796312", 
     "firstName":"firstName796312", 
     "lastName":"lastName796312", 
     "isActive":true, 
     "phoneNumbers":{"phoneNumberId":88,"number":796312796312}, 
     "addresses":{"addressId":298,"country":"CANADA","provinceOrState":"ONTARIO","address":"address796312","city":"Greater Sudbury","postalCode":"postalCode796312"}, 
     "emails":{"emailId":88,"email":"[email protected]"} 
     }] 
    ,"pagination":{"pageSize":10,"pageNumber":2,"totalItems":49}}} 

所以,我已經有一個函數來解析這個響應,如下所示。我想利用這個解析響應與jqGrid的,因爲在我的應用程序有許多情況下,這樣的:

{"currentPage" : "1", "totalRecords" : 2, "pageSize" : 3, 
    "myData" :[{ 
     "id" : "1", "name" : "firstName824504", "email" : "[email protected]" 
    },{ 
     "id" : "3", "name" : "firstName796312", "email" : "[email protected]" 
    }] 
}; 

===最終代碼===

我得到它的工作。謝謝您的幫助。這是我的功能示例。我希望它可以在未來幫助其他人。

$(document).ready(function() { 
    /* 
    * Here I will have a very complex logic to parse the response from the server in something jqGrid can understand. 
    * Right now it is just a hard-coded string to make thinks easer to understand 
    */ 
    function parseResponse(responseText){ 
     var parsedResponse = '{"currentPage" : "1", "totalRecords" : 5, "pageSize" : 3, "pageTotal" : 2,' 
       + '"myData" :[{"id" : "1", "name" : "Name 1" },' 
       + '   { "id" : "3", "name" : "Name 3" },' 
       + '   { "id" : "2", "name" : "Name 2" }]' 
       + '}'; 
     return JSON.parse(parsedResponse); 
    }; 

    var myGrid = $('<table>').attr("id", "useraccount-search-datagrid"); 
    var myPager = $("<div>").attr("id", "useraccount-search-datagrid-pager"); 

    $("body").append(myGrid, myPager); 

    myGrid.jqGrid({ 
     pager : myPager, 
     // datastr: parsedResponse, // If I use these parameters and remove ajaxGridOptions then it will work fine with the local data 
     datatype : "json", 
     url: "../rush-controller-testing/userAccount/find", 
     mtype: "POST", 
     serializeGridData : function(data) { 
      // That is just a hard-coded example to make things easier to understand. Will change it to a more complex logic later. 
      return '{"SearchCriteria": {"keyword":"emai","orderByField":"userName","sortOrder":"DESC","pagination":{"pageSize":"10","pageNumber":"3"}}}'; 
     }, 
     ajaxGridOptions: { 
      contentType: "application/json; charset=utf-8", 
     }, 
     colModel : [ 
      { name : 'name', index : 'name', width : "500"} 
     ], 
     jsonReader: { 
      repeatitems: false, 
      root: function(data){ 
       //the actual data 
       var result = parseResponse(data); 
       return result.myData; 
      }, 
      total: function(data) { 
       //total pages for the query 
       var result = parseResponse(data); 
       return result.pageTotal; 
      }, 
      page: function(data){ 
       //current page of the query 
       var result = parseResponse(data); 
       return result.currentPage; 
      }, 
      records: function(data){ 
       //total number of records for the query 
       var result = parseResponse(data); 
       return result.totalRecords; 
      } 
     }, 
     rowNum : 3, 
     viewrecords : true, 
     height : "auto", 
     ignoreCase : true, 
     hidegrid: false 
    }); 

}); 
+0

服務器發回的這個「怪異格式」是什麼? –

+0

這不是一個錯誤只是一個響應(JSON格式)從服務器發回我必須解析。 – Rafa

回答

2

您以錯誤的方式使用jqGrid選項。瞭解jqGrid需要「知道」urldatatype等參數很重要。如果未指定datatype,則將使用默認值"xml"

您不應該覆蓋已存在於jqGrid中的關於ajaxGridOptions的參數。所以你應該正確使用jqGrid。如果URL "../rush-controller-testing/userAccount/find"您在其中parsedResponse包括格式返回數據,那麼你的代碼可以瞭解以下信息:

myGrid.jqGrid({ 
    url: "../rush-controller-testing/userAccount/find", 
    datatype: "json", 
    mtype: "POST", 
    pager: "#useraccount-search-datagrid-pager", 
    serializeGridData : function(data) { 
     // the function is DUMMY. it MUST be replaced 
     return '{"SearchCriteria": {"keyword":"emai","orderByField":"userName","sortOrder":"DESC","pagination":{"pageSize":"10","pageNumber":"2"}}}'; 
    }, 
    ajaxGridOptions: { contentType: "application/json; charset=utf-8" }, 
    colModel: [ 
     { name: 'id', key: true, width: 100 } 
     { name: 'name', width: 400 } 
    ], 
    jsonReader: { 
     root: "myData", 
     page: "currentPage", 
     records: "totalRecords", 
     repeatitems: false 
    }, 
    rowNum: 3, 
    gridview: true, 
    autoencode: true, 
    viewrecords: true, 
    height: "auto", 
    ignoreCase: true, 
    hidegrid: false 
}); 

真正需要repeatitems: false財產的jsonReader內的使用情況。我認爲您不需要使用jQuery.ajax的任何converters

+1

非常感謝您的詳細解答。我將嘗試這些更改並儘快通知您。(順便說一下,你已經在stackoverflow上寫了很多其他很好的答案,謝謝你的貢獻)。 – Rafa

+0

@YoriKusanagi:不客氣!我很高興我的舊答案可以幫助你。順便說一下,在許多情況下,可以使用'prmNames'選項來自定義將被髮送到服務器的參數。 'serializeGridData'只是信息轉換的最後一步。 – Oleg

+1

在這一點上,我真正的挑戰是解析來自服務器的響應。我一直在研究這個問題好幾個小時,但無法弄清楚什麼是錯誤的。任何幫助將不勝感激。 – Rafa

0

查看jqGrid wiki上的data manipulation pages。我認爲jsonReader可能是你要找的。

+0

我試過使用jsonReader,但它沒有在我的情況下工作。從服務器發送的數據非常不同。因此,我需要一個複雜的解析函數來處理它。 – Rafa