2011-12-15 147 views
3

PHP json_encode没有返回正确的JSON编码的字符串

var posturl = '/admin/getparamdetails/'; 
    var data = "adnetworkId="+adnetworkId; 
    $.ajax({ 
     type: "POST", 
     url: posturl, 
     data : data, 
     datatype: "json", 
     success: function(msg){ 
      //$("#displayPramForm").html(msg); 
      //alert('hello'+msg.length+' '+msg.hello.length); 
      console.log(msg); 
      if(msg!='') 
      { 
       alert(msg.hello); 
      } 
     }, 
     failure: function(msg){} 
    }); 
在我的PHP后端功能

,我使用json_encode简单阵列上,如下所示:

$json_encoded_string = json_encode(array("hello"=>'abc')); 
echo $json_encoded_string; 
die;    

警报(msg.hello)回报未定义我。这里出了什么问题? 此外,在我的的console.log我能够得到的输出为:

{"hello":"abc"}  

回答

2

在返回数据使用parseJSON

if (msg) { 
    msg = $.parseJSON(msg); 
    alert(msg.hello); 
} 
1

你要发送数据的内容类型“应用/ JSON”,否则将无法正常工作。

只需添加以下在你的PHP文件:

header('Content-type: application/json'); 
+0

不,它仍然没有工作。 – debaShish 2011-12-15 10:45:34

+0

它应该是```header('Content-Type:application/json');``` – srph 2015-01-08 21:00:51