首頁 >後端開發 >C++ >如何使用帶有城市映射的 JSON 回應在 jqGrid 中顯示多個表中的資料?

如何使用帶有城市映射的 JSON 回應在 jqGrid 中顯示多個表中的資料?

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-01-23 07:11:38496瀏覽

How to Display Data from Multiple Tables in jqGrid Using a JSON Response with City Mapping?

jqGrid:處理多個相關表中的資料

jqGrid,一個強大的 jQuery 插件,擅長顯示來自各種來源的資料。此範例示範如何有效呈現兩個互連表中的資料:StudentsCities.

Students 表格使用城市 ID 作為外鍵,引用 Cities 表取得城市名稱:

<code>Students:
| SID | SNAME | CITY |
|---|---|---|
| 1 | ABC | 11 |
| 2 | XYZ | 12 |
| 3 | ACX | 13 |

Cities:
| CID | CNAME |
|---|---|
| 11 | Chennai |
| 12 | Mumbai |
| 13 | Delhi |</code>

所需的輸出格式是一個jqGrid,顯示學生資訊和實際城市名稱:

SID SNAME City
1 ABC Chennai
2 XYZ Mumbai
3 ACX Delhi
4 KHG Banglore
5 ADF Hyderabad
6 KKR Kolkatta

為了實現此目的,伺服器端回應的結構包括一個 cityMap,它將城市 ID 轉換為名稱:

<code class="language-json">{
    "cityMap": {"11": "Chennai", "12": "Mumbai", "13": "Delhi"},
    "rows": [
        { "SID": "1",  "SNAME": "ABC", "CITY": "11" },
        { "SID": "2",  "SNAME": "XYZ", "CITY": "12" },
        { "SID": "3",  "SNAME": "ACX", "CITY": "13" },
        { "SID": "4",  "SNAME": "KHG", "CITY": "13" },
        { "SID": "5",  "SNAME": "ADF", "CITY": "12" },
        { "SID": "6",  "SNAME": "KKR", "CITY": "11" }
    ]
}</code>

客戶端 jqGrid 程式碼利用 beforeProcessing 事件使用 cityMap 動態更新列屬性。這可確保顯示正確的城市名稱。 這裡沒有直接使用formatter: "select"選項,但是運行時動態更新列選項的原理保持不變。

這是客戶端程式碼的簡化表示:

<code class="language-javascript">var filterToolbarOptions = {defaultSearch: "cn", stringResult: true, searchOperators: true},
    removeAnyOption = function ($form) { /* ... (function remains unchanged) ... */ },
    $grid = $("#list");

// ... (other code remains largely unchanged) ...

$grid.jqGrid({
    // ... (colModel remains largely unchanged) ...
    beforeProcessing: function (response) {
        // ... (logic to handle cityMap and update column properties) ...
    },
    jsonReader: { id: "SID"}
});
// ... (rest of the code remains largely unchanged) ...</code>

beforeProcessing 函數將在 jqGrid 渲染網格之前使用回應中的 cityMaprows 資料中的數位城市 ID 替換為對應的城市名稱。 這種方法避免了複雜的客戶端資料操作並保持邏輯簡潔。

以上是如何使用帶有城市映射的 JSON 回應在 jqGrid 中顯示多個表中的資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn