简体   繁体   中英

Loop through PHP associative array in javascript or jquery

I have the following PHP associative array output as a response to jquery post request:

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

How can iterate through the above PHP associative array in javascript or jquery? Is this possible? or should I print the output of PHP in another way? I have access to the PHP as well

In PHP just echo using json_encode :

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

In Jquery:

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

Here's what I use in a similar application:

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
    }
});

For the looping part, this question/answer might be helpful: How to Loop through plain JavaScript object with objects as members?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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