简体   繁体   English

在javascript或jquery中循环遍历PHP关联数组

[英]Loop through PHP associative array in javascript or jquery

I have the following PHP associative array output as a response to jquery post request: 我有以下PHP关联数组输出作为对jquery帖子请求的响应:

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

How can iterate through the above PHP associative array in javascript or jquery? 如何在javascript或jquery中迭代上述PHP关联数组? Is this possible? 这可能吗? or should I print the output of PHP in another way? 还是应该以其他方式打印PHP的输出? I have access to the PHP as well 我也可以使用PHP

In PHP just echo using json_encode : 在PHP中,只需使用json_encode回显:

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

In Jquery: 在Jquery中:

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

Here's what I use in a similar application: 这是我在类似应用程序中使用的:

PHP: 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: 使用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
    }
});

For the looping part, this question/answer might be helpful: How to Loop through plain JavaScript object with objects as members? 对于循环部分,此问题/答案可能会有所帮助: 如何以对象作为成员循环遍历普通JavaScript对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM