2013-08-02 45 views
0

這是我的jquery代碼:發佈JSON到PHP腳本服務器端失敗

var jsObj = {"user_id":5, "login":"hsm"}; 
var str_json = JSON.stringify(jsObj); 
$.post("json_handler.php", str_json) 
    .done(function(){ 
     alert('data sent successfully'); 
     window.location = "http://localhost/quranMapping/php/json_handler.php"; 
    }) 
    .fail(function(){ 
     alert('fail'); 
    }); 

注:我做了重定向檢查出哪裏出了問題。

這是我的PHP代碼(json_handler.php文件):

<?php 

//create a DB connection 
$con=mysqli_connect("127.0.0.1","root","","my_db"); 

$input = file_get_contents('php://input'); 
$result = json_decode($input); 

echo $result->user_id; 
mysql_close($con); 
?> 

由於錯誤看看所附圖片,

我怎樣才能糾正這些問題呢?

enter image description here

更新:當我用$input = $_POST['str_json']錯誤是undefined index

+0

你得到json_decode任何錯誤? http://php.net/manual/en/function.json-last-error.php – JimL

+0

以後參數爲: $ input = $ _POST ['str_json']; – Aditya

+0

哪條線是17號線? –

回答

1

的json_decode可能失敗,返回NULL值。請執行var_dump($result)var_dump($input)以查看您從客戶端和json_decode獲得的內容。

+0

同樣的問題,通過它,它不是誰downvoted你的答案:) –

0

你爲什麼不嘗試使用

JS:

var jsObj = {"user_id":5, "login":"hsm"}; 
var str_json = JSON.stringify(jsObj); 
$.post("json_handler.php", {"str_json" :str_json}) 
      .done(function(){ 
       alert('data sent successfully'); 
       window.location = "http://localhost/quranMapping/php/json_handler.php"; 
      }) 
      .fail(function(){ 
       alert('fail'); 
      }); 

PHP:

<?php 

//create a DB connection 
$con=mysqli_connect("127.0.0.1","root","","my_db"); 

$input= $_POST['str_json'] 
$result = json_decode($input); 

echo $result->user_id; 
mysql_close($con); 

?> 
+0

你錯過了一個'{'和'} –

+0

謝謝凱文我複製粘貼該代碼在一個瞬間:) – Aditya

+0

它不起作用: ( –

相關問題