2012-10-14 94 views
1

我一直在stackOverflow和Google搜索整晚,以找到一種方法來使我的ajax工作。我想使用json將我的數據發佈到php表單,然後在php中解碼json並處理它們。在php中處理後,返回json中的一些數據。jQuery發佈JSON並通過PHP解碼

下面是我用來發送json到php的jQuery代碼。

 JSONobj = { 
      firstname : "david", 
      email : "[email protected]" 
     }; 

     var JSONstr = JSON.stringify(JSONobj); 

      $.ajax({ 
       type: "POST", 
       url: "Process.php", 

       data: {info: JSON.stringify(JSONobj)}, 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function(data){ 
          alert(data.newName); 
         } 
      }); 

但是解析JSON後,我的頭是看起來像這樣:

enter image description here

,我應該把我的PHP文件?

<?php  
$myJson =json_decode($_POST['info'], true); 


    // modify the name and return the data in json back 
?> 

感謝

回答

1

的問題是,JSON.stringfy()的方法是使用數組轉換成JSON

所以在你的PHP文件中使用使用JSONobj=new array();

data: {info: JSONstr}, 
or 
data:JSONstr; 

$myjson->firstname; 

// than create a array using 

$newarray=array("firstname"=>$firstname,"lastname"=>$lastname); 


echo json_encode($newarray) 
+0

我的第一個問題是jQuery中的json解析不正確。我應該怎麼做? – user1725155

+0

當我發送json時,在我的Header中看起來像這樣:info =%7B%22firstname%22%3A%22david%22%2C%22email%22%3A%22daivd%40gmail.com%22%7D – user1725155

+0

@ user1725155你在php文件中得到了什麼? – StaticVariable

0

這是我必須做的:

$list = stripcslashes(utf8_encode(urldecode($_POST["list"]))); 
$obj = json_decode($list); 

然後我看見對象時我做的var_dump($ OBJ);