Php jQuery$.post未返回JSON数据

Php jQuery$.post未返回JSON数据,php,json,jquery,Php,Json,Jquery,我读过多篇类似的文章,我的代码似乎与建议相符,但仍然没有返回数据 以下是我的JS: $.post('php/get_last_word.php', { user_id : userID }, function( data ) { currentLanguage = data.language_id; currentWord = data.word_id; console.log("currentLan

我读过多篇类似的文章,我的代码似乎与建议相符,但仍然没有返回数据

以下是我的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数组被回送,但它不会在
数据中结束,因为
currentLanguage
currentWord
没有被填充。这是异步性的问题吗?还是别的什么?

确保从PHP脚本返回到变量的json有效

如果json对象是这样的

{"language_id":"1","word_id":"1"}
您可以像这样访问这些值

currentLanguage = data.language_id;
currentWord = data.word_id;
示例JsFiddle

您可以使用来验证jSon的格式是否正确

在post请求中指定
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调用的缩写,数据类型为json


尝试将您的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
));

?>

这样会更有条理,别忘了设置内容类型


希望有帮助。

为什么它在
循环中?您是否期望不止一个结果?如果是这样,那就是你的问题;否则,只需将其设置为
(如果
)。还有一个事实是它们被称为
language\u id
word\u id
,而不是
language
word
…谢谢,我错过了。但是,它仍然没有返回任何已修复的内容。@SmoothAlmonds:请参阅我的更新答案和示例链接。我猜你的jSon是无效的。您不需要jSon.Fixed中的“成功完成”。这是一个愚蠢的错误。在连接之后和返回数据之前,我在php文件中有一个“echo'Connected successfully';”语句,所以首先返回的是这个语句。谢谢