【问题标题】:Json_encode returns string instead of objectJson_encode 返回字符串而不是对象
【发布时间】:2016-06-07 05:50:59
【问题描述】:

我有一个 php 文件,它对数据进行一些操作,然后以json 格式(假设)发送数据。

然后我使用 ajax 在 js 文件中接收数据。是跨域操作,那我需要使用jsonp。

问题是我收到了错误

对象 {readyState: 4, status: 200, statusText: "success"} parsererror - 错误:jQuery1123030211047915085665_1465277732410 是 未调用(…)

我认为这是因为我没有以 json 对象的形式接收数据,而是以简单字符串的形式接收数据(当我将数据类型从 jsonp 更改为 text 时,它会转到 .done 块)。

如何将数据作为 json 对象而不是简单字符串接收?

代码:

php:

if ( $moeda ==='SEK' ){

 foreach($result as $r){ //$result is an array with the result of a sql query

//here I do some verifications, that depending on the circunstance, calculate and replace 
//the value of the $r['price'] field.

    if($r['currency'] === "SEK"){
        $valor = $r['tprice'];
        $r['tprice'] = number_format($valor,2,'.','');

    }else if ($r['currency'] === "BRL"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];  
        $r['tprice'] = number_format( ( converteBRL_SEK($dat,$valor) ) ,2,'.','');


    }else if ($r['currency'] === "USD"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];
        $r['tprice'] = number_format(( converteUSD_SEK($dat,$valor) ),2,'.','');     

    }else if ($r['currency'] === "EUR"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];
            $r['tprice'] = number_format(( converteEUR_SEK($dat,$valor) ),2,'.','');    

    }
    else{
        echo 'error';
    }
$retorno['dados'] = $r;   
// using the GET callback because I'm using jsonp.
echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).')'; 


}

编辑: 我忘了发布javascript代码,这里是:

代码:

function buildTableDetail(p_sts,p_ar){  
    $('#tb_detail').empty();
    return $.ajax({
       type:'GET',
       crossDomain:true,
       url:'http://localhost/files/montar_detail_local.php?callback=?',// I use a real url, localhost just for the example
       dataType:'jsonp',
       data: {area:p_ar,
              st:p_sts},
       beforeSend: function(){
       $('#t_detail').css('opacity','1.0');  
           console.log(p_ar);
        console.log(p_sts);
       }    


    }).done(function(data){
        //after I get the data, I build a table, and format some values here...
         $('#tb_detail').empty();

         console.log("AREA:"+p_ar);
         for (i = 0; i < data.dados.length; i++) { 
             $('#tb_detail').append('<tr> <td>'+data.dados[i].proposal+
                                    '</td><td class="h_detail old_no" >'+data.dados[i].old_no+
                                    '</td><td class="h_detail emissao" style="white-space: nowrap;">'+data.dados[i].emissao+
                                    '</td><td class="h_detail area">'+data.dados[i].area+
                                    '</td><td class="h_detail country">'+data.dados[i].country+
                                    '</td><td class="h_detail ec_name">'+data.dados[i].ec_name+
                                    '</td><td class="h_detail distributo">'+data.dados[i].distributo+
                                    '</td><td class="h_detail project">'+data.dados[i].project+
                                    '</td><td>'+float2moeda(data.dados[i].tprice)+
                                    '</td><td class="h_detail gm">'+data.dados[i].gm+
                                    '</td><td >'+data.dados[i].prob+
                                    '</td><td class="h_detail st">'+(data.dados[i].st).substr(0,1)+'</td></tr>');


                console.log(data.dados[i].proposal);
                console.log(data.dados[i].distributo);
            }
})
.fail(function(data, textStatus, errorThrown){
        alert("Erro na operação.");
        console.log(data);
        console.log(textStatus);
        console.log(errorThrown);
     })

}

EDIT2:

刚刚更新了这一行:

echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).')'; 

到这里

echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).');'; 

并且错误不再显示。但是,它没有进入for 循环,也没有显示任何数据。我使用了console.log(data.dados.lenght),它返回“未定义”给我,所以我不能循环。

有什么想法吗?

【问题讨论】:

  • 您还需要发布 javascript。
  • 抱歉,刚刚更新了问题。

标签: javascript php jquery json ajax


【解决方案1】:

JSON 只不过是一个字符串。如果您使用 jQuery 将 json 字符串转换为对象,请在 javascript 中使用 $.parseJSON。

【讨论】:

  • 是的,我知道,但是我必须使用 json_encode 在服务器和客户端之间进行其他数据操作,并且它通常作为 Json 对象接收。包括这个例子。在我写了 if 并进行转换之后,它就开始大喊这个错误。在此之前,我只是在做一个 sql 查询,获取一个数组,然后使用 json_encode 将数据作为json 对象发送,它正在工作
【解决方案2】:

尝试以下方法:

  if ( $moeda ==='SEK' ){

 foreach($result as $r){ //$result is an array with the result of a sql query

//here I do some verifications, that depending on the circunstance, calculate and replace 
//the value of the $r['price'] field.

    if($r['currency'] === "SEK"){
        $valor = $r['tprice'];
        $r['tprice'] = number_format($valor,2,'.','');

    }else if ($r['currency'] === "BRL"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];  
        $r['tprice'] = number_format( ( converteBRL_SEK($dat,$valor) ) ,2,'.','');


    }else if ($r['currency'] === "USD"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];
        $r['tprice'] = number_format(( converteUSD_SEK($dat,$valor) ),2,'.','');     

    }else if ($r['currency'] === "EUR"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];
            $r['tprice'] = number_format(( converteEUR_SEK($dat,$valor) ),2,'.','');    

    }
    else{
        echo 'error';
    }
$retorno['dados'][] = $r;   //append to the array

}
   // using the GET callback because I'm using jsonp.
echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).');'; //echo the valid call of the callback 

【讨论】:

  • 将在这里尝试并在一分钟内回答
  • 嘿,谢谢!它解决了一半的问题! 我不再收到错误消息但它什么也没给我。没有信息来
  • 当你控制数据时你会收到什么?
  • 我只收到一个注册表,但它必须远不止一个
  • 谢谢你!我按照你说的更新并工作了!非常感谢!
【解决方案3】:

尝试使用JSON_FORCE_OBJECT 而不是JSON_PRETTY_PRINT

类似的东西。

echo $_GET['callback'] . '('.json_encode($retorno,JSON_FORCE_OBJECT).')';

【讨论】:

  • 您好,我已经尝试过了,但是没有用。它一直在喊同样的错误
  • 您是否尝试使用dataType:'json', 而不是dataType:'jsonp',
  • 是的,它给了我一个跨域错误。是跨域操作,那我得用jsonp。在这种情况下,json 对我不起作用
  • 在你的 .htaccess 中添加 Header always set Access-Control-Allow-Origin "*" 并尝试使用 json。
  • 如果你仔细观察,你会发现他在 localhost 上,在他的浏览器中他有 127.0.0.1,在 ajax 中他正在 ajaxing localhost 而不是 127.0.0.1 这导致了 CORS 错误
猜你喜欢
  • 2012-09-28
  • 2017-07-18
  • 2011-07-29
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多