2010-11-13 45 views
1

我的PHP代碼如何使用PHP多維數組中的jQuery

$classObject = new class_functions(); 
$city = $_REQUEST['city']; 
$locations[] = $classObject->populate_locations($city); 
echo "var result=".json_encode($locations); 

我的jQuery

$("select[name='city']").change(function(){ 
    var city = $("select[name='city']").serialize(); 
    $.ajax( 
    { 
     type: "POST", 
     url: "jquerycalls.php", 
     data: city, 
     beforeSend: function() { 
     //alert("asdf"); 
     }, 
     success: function(data1) { 
     // multidimensional array over here 
     } 

    }); 
}); 

結果我從成功的警告得到:jQuery的一部分

var result=[[["Aabpara Market"],["AGHOSH"],["Akbar Town"],["Alipur Farash"],["Atomic Energy Employee Society"],["AWT"],["B-17"],["Bahria Town"],["Bani Gala"],["Bharakhu"],["Blue Area"],["British Homes Colony"],["Burma Town"],["CBR Town"],["Chak Shahzad"],["Chaklala Scheme 3"],["Civic Centre"],["D-12"],["D-13"],["D-16"],["D-17"],["D-18"],["Darussalam Co-Op Society"],["Defence Phase-2"],["Defence Phase-I"],["DHA Valley"],["Diplomatic Enclave"],["E-6"],["E-7"],["E-11"],["E-12"],["E-14"],["E-16"],["E-17"],["E-18"],["Engineers Cooperative Housing Society"],["F-10"],["F-11"],["F-13"],["F-15"],["F-16"],["F-17"],["F-5"],["F-6"],["F-7"],["F-8"],["Fateh Jang"],["G-5"],["G-6"],["G-7"],["G-8"],["G-9"],["G-10"],["G-11"],["G-13"],["G-14"],["G-15"],["G-16"],["G-17"],["Ghauri Town"],["Gulzar Housing Scheme"],["H-13"],["H-15"],["H-8"],["H-9"],["Humak"],["I-8"],["I-9"],["I-10"],["I-11"],["I-12"],["I-14"],["I-15"],["I-16"],["I-17"],["Islamabad Airport"],["Islamabad Cooperative Housing Society"],["J and K Zone-V"],["Jinnah Garden"],["Jinnah Super Market"],["Jinnah Town"],["Judicial Town"],["Kahuta"],["Korang Town"],["Margalla Town"],["Melody Market"],["Motorway City"],["Muree Expressway"],["National Police Foundation"],["Naval Anchorage"],["New Shakrial"],["O-9"],["Orchard Scheme"],["P.W.D Housing Scheme"],["PAF Tarnol"],["Pakistan Housing Society"],["Pakistan Town"],["PECHS"],["Rawal Town"],["River Garden"],["Roshan Pakistan Scheme"],["Sangjani"],["Sawan Garden"],["Shehzad Town"],["Sihala"],["Sohan Valley"],["Super Market"],["Tarlai"],["Top City 1"],["University Town"],["Wapda Town"],["Zero Point"],["Zone 5"]]] 

如何使用從PHP代碼返回的多維數組?

回答

1

更改PHP來:

echo json_encode($locations); 

然後在JQuery的,你可以這樣做:

success: function(data1) { 
    var result = eval(data1); 
    result[0][0]; 
} 

,您可以訪問其他元素的數組一樣的方法。

1

最簡單的方法是使用json_encode將其轉換爲可以作爲JavaScript對象進行評估的字符串。

即:

 
$locations[] = $classObject->populate_locations($city); 
echo "var result = " . json_encode($locations) . ";" // valid JavaScript. 
+0

檢查問題中的編輯。添加json_encode後,我使用了一個警報。結果顯示在問題的最後。如何將其轉換爲數組或獲取jQuery中的值? – booota 2010-11-13 04:54:16