【问题标题】:How do I interact correctly between jquery and php using json如何使用 json 在 jquery 和 php 之间正确交互
【发布时间】:2014-09-05 13:55:32
【问题描述】:

我尝试将字符串解析为 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文件中的字符串响应,发现字符串gehts \r\n\r\n\r\n 到最后。即使我没有响应 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

现在很高兴知道为什么即使我没有回应任何内容也会收到这些新行

但我认为这不适合头部问题

【问题讨论】:

标签: php jquery json


【解决方案1】:

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

<?php error_reporting(0); ?>

由于您使用的是 mysql_query,它会为导致错误的已弃用函数提供警告消息。整个警告消息以不符合您期望的格式返回到您的页面。该语句将抑制警告,应该没问题。但我建议你使用 PDO 或 mysqli。

【讨论】:

  • 你能分享一下test.php你在你的index.php中也用过这个东西吗。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多