【问题标题】:php json_encode not returning proper json encoded stringphp json_encode 没有返回正确的 json 编码字符串
【发布时间】:2011-12-15 10:28:10
【问题描述】:

我正在使用接受 json 响应的 jquery ajax 调用:

 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;               

alert(msg.hello) 为我返回 undefined。这里出了什么问题? 另外,在我的 console.log 中,我可以得到如下输出:

{"hello":"abc"}     

【问题讨论】:

    标签: php jquery ajax json


    【解决方案1】:

    在返回数据上使用parseJSON

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

    【讨论】:

      【解决方案2】:

      您必须将数据作为 Content-Type "application/json" 发送,否则将无法正常工作。

      只需在您的 PHP 文件中添加以下内容:

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

      【讨论】:

      • 应该是header('Content-Type: application/json');
      猜你喜欢
      • 1970-01-01
      • 2014-06-14
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2014-09-27
      相关资源
      最近更新 更多