如何使用json在jquery和php之间正确交互


How do I interact correctly between jquery and php using json

我试图将字符串解析为jquery对象,但我没有得到正确的格式。不知道错误在哪里。
我的目标是从数据库加载数据,并将其放入对话框中,在那里我可以更新用户

我在js文件中有一个帖子请求,按下按钮执行:

$.post("index.php", { "id": ID , "action": "edit_row"},
    function(input){
        console.log(input); //{"id":"1","fname":"Test","lname":"Name"}
        console.log(input.id); //undefined
        var data = $.parseJSON(input); //Uncaught SyntaxError: Unexpected token
        console.log(data); //not possible
        console.log(data.id); //not possible
        test = {"id":"1","fname":"Test","lname":"Name"};
        console.log(test); // I get the object
        console.log(test.id); //1
    }); // when I use ',"json"' between the brackets nothing happens, no logs are written in console

我的index.php返回从数据库加载的字符串:

$query = "SELECT `id`, `fname` , `lname` FROM `user` WHERE `id`= ".$id; //it's just one row
$result = sql_query($query);
    while ($row= mysql_fetch_assoc($result)){
            $data = $row;
    };
echo json_encode($data);
//php function
function sql_query($query){
$result = mysql_query($query);
if(!$result) {
    die("Request Failed: " . mysql_error());
}   
   return $result;
}

编辑2

我分析了js文件中的字符串响应,发现字符串一直到最后。即使我没有从php文件中做出任何响应。。。

我认为在处理ajax请求时,我的index.php中有损坏的东西。

我在另一个php文件上完成了请求,在那里它可以毫无问题地工作。

$.post("test.php", { "id": ID , "action": "edit_row"},
    function(input){
        console.log(input); // I get the object
        console.log(input.id); //1
        //testdata below
        test = {"id":"1","fname":"Test","lname":"Name"};
        console.log(test); // I get the object
        console.log(test.id); //1
    },"json");  //using ',"json"' is working on the test.php file now

现在,即使我什么都不回应,也很高兴知道为什么我会收到这些新线路

但我认为这不符合

的首要问题

在index.php页面顶部使用此语句

<?php error_reporting(0); ?>

由于您使用的是mysql_query,因此它会为导致错误的不推荐使用的函数发出警告消息。整个警告消息将返回到您的页面,该页面的格式与您期望的格式不同。此语句将取消显示警告,应该没问题。但我建议你使用PDO或mysqli。