簡體   English   中英

在javascript或jquery中循環遍歷PHP關聯數組

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

我有以下PHP關聯數組輸出作為對jquery帖子請求的響應:

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

如何在javascript或jquery中迭代上述PHP關聯數組? 這可能嗎? 還是應該以其他方式打印PHP的輸出? 我也可以使用PHP

在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

這是我在類似應用程序中使用的:

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

對於循環部分,此問題/答案可能會有所幫助: 如何以對象作為成員循環遍歷普通JavaScript對象?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM