簡體   English   中英

jQuery $.post 不返回 JSON 數據

[英]jQuery $.post not returning JSON data

我已經閱讀了多篇關於此的類似帖子,我的代碼似乎符合建議,但仍然沒有返回數據。

這是我的 JS:

    $.post('php/get_last_word.php', { user_id : userID },
        function( data ) {
            currentLanguage = data.language_id;
            currentWord = data.word_id;
            console.log("currentLanguage = " + currentLanguage)
            console.log("currentWord = " + currentWord);        
    },'json');

以及相關的php:

$user_id=$_POST['user_id'];

mysql_select_db(wordsicle_search); 

$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);

while ($row = mysql_fetch_assoc($result)) {
    $encoded = json_encode($row);
    echo $encoded;
}

以及生成的日志:

Connected successfully{"language_id":"1","word_id":"1"} 

所以 json 數組被回顯,但它並沒有在data中結束,因為currentLanguagecurrentWord沒有被填充。 這是異步性的問題嗎? 或者是其他東西?

確保你有一個有效的 json 從你的 PHP 腳本返回你的變量

如果你的 json object 是這樣的,

{"language_id":"1","word_id":"1"}

您可以像這樣訪問值

currentLanguage = data.language_id;
currentWord = data.word_id;

示例 JsFiddle http://jsfiddle.net/NuS7Z/8/

您可以使用http://jsonlint.com/來驗證您的 jSon 的格式是否正確。

在您的發布請求中指定json作為數據類型值將確保響應以json格式返回到成功回調。

$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
        currentLanguage = data.language_id;
        currentWord = data.word_id;
});

您也可以使用getJson來簡單地獲取 json 數據。 getJson 是 ajax 的簡寫 Call with datatype as json

http://api.jquery.com/jQuery.getJSON/

嘗試將您的 JS 更改為:

 $.getJSON('php/get_last_word.php', { user_id : userID },
        function( response ) {
            if (response.success) {
                currentLanguage = response.data.language_id;
                currentWord = response.data.word_id;
                console.log("currentLanguage = " + currentLanguage)
                console.log("currentWord = " + currentWord);     
            } else {
                alert('Fail');
            }   
    });

和您的 PHP 至:

<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];

mysql_select_db(wordsicle_search); 

$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);

while ($row = mysql_fetch_assoc($result)) {
    $success = true;
    $data = $row;
}

// I generally format my JSON output array like so:

// Response
header('Content-Type: application/json');
echo json_encode(array(
    'success' => $success,
    'data' => $data
));

?>

這樣更有條理,不要忘記設置內容類型。

希望有所幫助。

暫無
暫無

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

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