2012-03-29 59 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); 
}