2015-04-07 63 views
3

我使用這個jQuery的功能,通過Ajax獲得的數據返回:數據未從阿賈克斯POST

function addContentPrt(cid){ 
    $.ajax({ 
    url: "<?=parseLink('addContent.php')?>", 
    type: "POST", 
    cache: true, 
    dataType:'json', 
    data: {id: cid}, 
    success: function(returnedData){ 
     console.log(returnedData); 
    }, 
    error: function (xhr, tst, err) { 
     console.log(err); 
    } 
    }); 
} 

,並在接收端:

<? 
    header("Content-Type: application/json", true); 

    if(isset($_POST['id'])) { 
    $id = $_POST['id']; 
    } 

    $sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id"); 

    $r = mysql_fetch_array($sql); 
    echo $r['title']; 
    echo $id; 
?> 

echo $id不會返回到AJAX,但不$r['title'] ,並在控制檯中執行null。如果我添加一些虛擬文本,如hello world,我得到一個合成器錯誤SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}

這可能是什麼原因,我該怎麼做才能修復它?

+4

讀變量$r你返回一個字符串,而不是JSON。 –

+0

在你的mysql_fetch_array上添加一個標誌MYSQL_ASSOC。否則你不會有數組鍵作爲標題..爲了測試更好的print_r($ r);要檢查你在$ r – Svetoslav

+0

你有什麼,你應該看看json_encode。 – Jai

回答

4
<? 
    header("Content-Type: application/json", true); 

    if(isset($_POST['id'])) { 
    $id = $_POST['id']; 
    } 

    $sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id"); 

    $r = mysql_fetch_array($sql); 
    echo json_encode('id' => $id, 'title' => $r['title']); 
?> 

,並在阿賈克斯成功:

success: function(returnedData){ 
    console.log(JSON.parse(returnedData)); 
}, 
0

在ajax中,您將數據類型指定爲json,這是從服務器獲得的格式,所以爲了獲得結果,您需要從服務器返回json結果。通過使用json_encode($ r),其中$ r可以是任何數組。

+0

我這樣做,它仍然返回'null' – raccon

+0

...或自己創建數組並將其傳回: '$ results = ['id'=> $ id,'title'=> $ r ['title' ]]; echo json_encode($ results);' 哦,你需要提供具體的頭文件。檢查此主題: http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – mzografski

+0

你確定$ r ['標題']或$ id是在服務器端設置? –

0

return json_encode($r);那麼您可以在sucess