以下に示すように、ajax 呼び出しから json データを取得しています。
/*
* Get list of vendors and populate table
*/
function getVendors() {
$
.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/getMVendors?version=2",
dataType : "json",
success : function(json) {
//add element to vendors array
$.each(json.resultSet.merchandiseVendor, function(index,item){
nameLocal = item.name;
numberLocal = item.number;
vendorData[vendorDataCounter] = {
name : nameLocal,
number : numberLocal
}
vendorDataCounter++;
});
initVendorTable();
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
initVendorTable() メソッドは、上記の ajax 呼び出しから取得したデータをテーブルに入力するためのものです。以下に示す initVendorTable() メソッド:
/*
* Initialize the table containing the list of vendors
*/
function initVendorTable() {
jQuery("#supplierTable").jqGrid({
datatype : "local",
height : 250,
colNames : [ 'Vendor Number', 'Vendor Name' ],
colModel : [ {
name : 'number',
index : 'name',
width : 200,
sorttype : "int"
}, {
name : 'name',
index : 'number',
width : 200
} ],
rowNum : 10,
rowList : [ 10, 20, 30 ],
sortname : 'number',
viewrecords : true,
sortorder : "desc",
caption : "Suppliers"
});
for(var i=0;i<=vendorData.length;i++){
$("#supplierTable").jqGrid("addRowData",i+1,vendorData[i]);
}
alert(vendorData);
}
ボタンのクリックから getVendors() メソッドを呼び出します。
$(function() {
$("#supplierSearchArea").dialog({
autoOpen : false,
height : 400,
width : 'auto',
modal : true,
title : 'Browse Suppliers'
});
$("#supplierPopupButton").click(function(e) {
$("#supplierSearchArea").dialog("open");
getVendors();
});
});
問題は、最初にボタンをクリックしてテーブルを含むポップアップが表示されたときに、テーブルが空であることです。これは、テーブルの作成に使用する配列が空であるためです。
コードをステップ実行した後、コード内で initVendorTable() メソッドの前に getVendors() メソッドを呼び出しているにもかかわらず、initVendorTable() メソッドが getVendors() メソッドの前に呼び出されることがわかりました。これはajaxの癖ですか?これを回避する方法について何か提案はありますか?