2016-02-05 36 views
-5

PHP代碼=>`的getJSON()回調不與PHP文件工作

<?php 
    //request data from the database 
    //code here to connect to database and get the data you want 

    /* Example JSON format 
    { 
     "item1": "I love jquery4u", 
     "item2": "You love jQuery4u", 
     "item3": "We love jQuery4u" 
    } 
    */ 

    //return in JSON format 
    echo "{"; 
    echo "item1: ", json_encode($item1), "\n"; 
    echo "item2: ", json_encode($item2), "\n"; 
    echo "item3: ", json_encode($item3), "\n"; 
    echo "}"; 
?> 

JS =>

$(document).ready(function(){ 
    //attach a jQuery live event to the button 
    $('#getdata-button').click(function(){ 
     $.get('json-data.php', function(data) { 
     //alert(data); //uncomment this for debug 
     //alert (data.item1+" "+data.item2+" "+data.item3); //further debug 
     $('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>"); 
     }); 
    }); 
}); 

請我一直剛纔問過和我不是包括細節,因此這一次香港專業教育學院當包括 除了這個我的控制檯沒有給出錯誤包括整個樣本。 謝謝`

+2

**永遠無法用手JSON **你的PHP代碼生成無效JSON。製造陣列,並使用['json_encode()'](http://php.net/manual/en/function.json-encode.php),以產生有效的JSON。 – JJJ

+1

如果你剛纔問,然後更新這個問題。它會再次在隊列中重置。不要再問同樣的問題! –

+5

的可能的複製[可以的getJSON()用於PHP?](http://stackoverflow.com/questions/35195273/can-getjson-be-used-for-php) – legoscia

回答

1

你應該如下頭添加到您的PHP文件:

header('Content-type: text/json'); 

除此之外,只要把你的數據直接到一個數組,然後使用json_encode。 你的PHP文件應該是這個樣子:

<?php 
header('Content-type: text/json'); 
$results = array("item1"=> "I love jquery4u", 
"item2"=> "You love jQuery4u", 
"item3"=> "We love jQuery4u" 
); 
echo json_encode($results); 
?> 

它會給你以下結果:

{ 
    "item1": "I love jquery4u", 
    "item2": "You love jQuery4u", 
    "item3": "We love jQuery4u" 
} 
+0

感謝您sir..this爲我工作好!自從很多天以來一直在嘗試很多...真誠的謝謝! –