2012-03-29 111 views
0

我有一個返回JSON數組的PHP文件。我需要提取數組名稱,在這種情況下,* Regulatory_Guidance_Library *使用jQuery作爲我的函數的$('#navHeaderTitle').text(arrayName);的變量。我不知道這是如何完成的。如何提取PHP JSON數組名稱

日Thnx的幫助

我在HTML文檔功能:

function loadNav(url, container, appendE) { 
     $.getJSON(url, function(data){ 
        var arrayName = ""; 
      $.each(data.Regulatory_Guidance_Library, function(){ 
       var newItem = $('#' + container).clone(); 
       // Now fill in the fields with the data 
       newItem.find("h1").text(this.label); 
       newItem.find("h2").text(this.title); 
       newItem.find("p").text(this.description); 
       // And add the new list item to the page 
       newItem.children().appendTo('#' + appendE) 
      }); 
      $('#navHeaderTitle').text(arrayName); 
      //transition(pageName, "show"); 
     }); 
    }; 

接受服務的PHP:

<?php 
//MySQL Database Connect 
include 'andaerologin.php'; 

mysql_select_db("andaero"); 
$sql=mysql_query("select * from regulatory_list"); 

$output = new stdClass(); 

while($row = mysql_fetch_assoc($sql)) { 
    $output->Regulatory_Guidance_Library[] = $row; 
} 

header('Cache-Control: no-cache, must-revalidate'); 
header('Content-type: application/json'); 
echo (json_encode($output)); 

mysql_close(); 
?> 

回答

1

修改PHP:

$output = array(); 
    /* used "key" as name...could change to suit your app*/ 
$output['key']='Regulatory_Guidance_Library'; 

while($row = mysql_fetch_assoc($sql)) { 
    $output['items'][]= $row; 
} 

AJAX:

$.getJSON(url, function(data){ 
     $.each(data.items, function(){ 
      var newItem = $('#' + container).clone(); 
      // Now fill in the fields with the data 
      newItem.find("h1").text(this.label); 
      newItem.find("h2").text(this.title); 
      newItem.find("p").text(this.description); 
      // And add the new list item to the page 
      newItem.children().appendTo('#' + appendE) 
     }); 
     $('#navHeaderTitle').text(data.key); 
     //transition(pageName, "show"); 
    }); 
+0

漂亮!你是一個很大的幫助。我會解決這個問題。 Thnx再次 – CelticParser 2012-03-30 00:01:41

1

對方回答可能是更有益的,但如果你想獲得一個對象的屬性與JavaScript的名字,你可以這樣做:

for (var name in data) { 
    alert(name); 
} 

在你的情況,因爲你只有一個屬性,你可以這樣做:

for (var name in data) { 
    $('#navHeaderTitle').text(name); 
}