[英]Echoing Variables within a JSON array
我正在嘗試訪問和顯示頁面上的json對象內的變量。 誰能告訴我為什么變量顯示三次?
my_array.php
<?php
$my_data=array(name=>"john",age=>"30", city=>"copenhagen");
// sending output
header('Content-Type: text/json');
echo json_encode($my_data,true);
?>
My_page.php
<script>
$(document).ready(function() {
$("button").click(function() {
$.getJSON("my_array.php", function(data) {
$.each(data, function(key) {
$("#showdata").append(data.city);
});
});
});
});
</script>
//Show the data further down the page.
<div id="showdata"></div>
顯示
copenhagencopenhagencopenhagen
那是因為您要從收到的json響應中迭代“每個”數據項,並且my_array.php中有3個key => value對
刪除“ $ .each(data,function(key){}”只會返回值“ city”一次
$(document).ready(function(){
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
});
用這個
my_array.php
<?php
$my_data = array(
name => "john",
age => "30",
city => "copenhagen"
);
// sending output
header('Content-Type: application/json');
echo json_encode($my_data, true);
?>
My_page.php
<div id="showdata"></div>
<button>Click Me!</button>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(e){
$.getJSON("test.php", function(data){
console.log(data);
$("#showdata").append(data.city);
});
});
});
</script>
這只會給您一個哥本哈根。
希望能幫助到你...
第一件事:
設置:
header("Content-Type: application/json");
以上:
echo json_encode($my_data,true);
在您的php文件上。
或在您的JavaScript上使用以下代碼段:
$.getJSON("my_array.php",function(data)
{
data=JSON.stringify(data);
$.each(data, function(key)
{
$("#showdata").append(data.city);
});
});
此外,無論是上面返回的數據還是返回對象的兩種方法,為了正確返回您的php文件,數據必須為:
$my_data=array(array(name=>"john",age=>"30", city=>"copenhagen"));
注意:php的json_encode上的關聯數組變成了對象。 json_encode上的非關聯數組仍保留為數組
我在猜測是因為您在頁面上有三個按鈕,而$ .each使選擇器嘗試:
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
您要重復3次,因為JSON對象中有三個鍵,
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log( "key + " " + val" );
});
查看JQuery文檔以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.