2014-09-30 60 views
0

我有以下PHP关联阵列输出作为jquery的交请求的响应:遍历PHP关联阵列中的JavaScript或jquery的

Array 
(
    [0] => Array 
    (
     [user] => 25 
    ) 
) 

如何可以通过以上PHP关联数组迭代在JavaScript或jquery的?这可能吗?还是应该以另一种方式打印PHP的输出?我有机会到PHP以及

+6

json_encode它。 – danronmoon 2014-09-30 19:07:26

+2

你将不得不发布比这更多的代码,例如JavaScript实际上是什么样子,你如何发送数组等? – adeneo 2014-09-30 19:07:32

+0

使用JSON是最好的选择IMO – 2014-09-30 19:12:08

回答

2

在PHP只是回声使用json_encode

$array = array(array('user' => 25)); 
echo json_encode($array); // [{"user":25}] 

jQuery中:

var data = $.parseJSON(jsonString); // '[{"user":25}]' 
console.log(data[0].user); // 25 
+0

我如何循环所有数组值?这只返回第一对...如果我有多个如何可以访问所有元素? – 2014-09-30 19:27:59

+0

您可以使用for循环。 'for(var i = 0; i 2014-09-30 19:30:36

+0

最后一个问题。如果'user'每次都像下面的json字符串那样:'[{“hey”:25},{“mate”:12}] – 2014-09-30 19:45:30

2

这是我在一个类似的应用程序中使用:

PHP :

header("Content-Type: application/json"); 
if ($_REQUEST["jsoncallback"]) { 
    $callback = htmlentities($_REQUEST["jsoncallback"]); 
} 
$output = json_encode($array); 
if ($callback) { 
    $output = $callback . "(" . $output . ")"; // I know the variables can be embedded in the strings, I don't care, I like it this way. 
} 
echo $output; 

的Javascript:

var getURL = "http://www.example.com/script.php?jsoncallback=?"; 
jQuery.ajax({ 
    dataType: "json", 
    url: getURL, 
    success: function(data){ 
     var obj = jQuery.parseJSON(data); 
     // now you can loop through the data object 
    } 
}); 

对于循环的一部分,这个问题/答案可能会有所帮助:How to Loop through plain JavaScript object with objects as members?