2014-09-05 46 views
0

我試圖解析一個字符串到jquery對象,但我沒有得到它在正確的格式。不知道錯誤在哪裏。
我的目標是從數據庫加載數據的把它變成一個對話框,在這裏我可以更新用戶我如何正確使用json和jQuery之間的交互jQuery

我在我的js文件中的POST請求時執行按下一個按鈕:

$.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拋出從數據庫返回的加載的字符串:2

我分析了串

$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; 
} 

編輯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 

現在,它會很高興地知道爲什麼我得到這些新的生產線,甚至當我不迴應任何事情

但我認爲這並不適合頭部querstion

+0

提示:請勿嘗試手動生成JSON。使用內置的語言功能。 – 2014-09-05 13:57:39

+1

@ʰᵈˑ那種無用的提示,因爲他在php中使用了json_encode。其他的東西只是測試數據,他把它放在 – Pinoniq 2014-09-05 13:58:20

+0

第1行的jQuery文件 - 看起來像他正在用手建造它... – 2014-09-05 13:58:52

回答

1

使用之上這個說法index.php網頁

<?php error_reporting(0); ?> 

由於您使用的mysql_query它給出了推薦的函數,這是造成該錯誤的警告消息。整個警告信息將返回到您的頁面,該頁面不符合您期望的格式。這個聲明會壓制警告,應該沒問題。但我建議你使用PDO或mysqli。

+0

你可以分享test.php你也使用過東西在你的index.php。 – 2014-09-06 06:55:41

相關問題