2016-06-07 76 views
-4

我有一個PHP文件,對數據做一些操作,然後以json格式發送數據(據推測)。Json_encode返回字符串而不是對象

然後我使用ajax接收js文件中的數據。這是一個跨域操作,那麼我需要使用jsonp。

麻煩的是,我收到了錯誤

Object {readyState: 4, status: 200, statusText: "success"} parsererror - Error: jQuery1123030211047915085665_1465277732410 was not called(…)

,我相信這是因爲我沒有收到數據作爲JSON對象,但作爲一個簡單的字符串(當我從JSONP更改數據類型將其發送到.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),它向我返回'undefined',所以我無法循環。

任何想法?

+0

您需要發佈的JavaScript以及。 – jeroen

+0

對不起,剛更新了這個問題。 – Lioo

回答

1

嘗試以下操作:

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 
+0

將在這裏嘗試並在一分鐘內回覆 – Lioo

+0

嘿,謝謝!它解決了一半的問題! **我不再收到錯誤**但它沒有返回給我。 – Lioo

+0

當你控制數據時你沒有收到什麼信息? – madalinivascu

2

JSON不過是一個字符串。如果您使用jQuery將json字符串轉換爲對象,請在JavaScript中使用$ .parseJSON。

+0

是的,我知道,但我必須使用json_encode在服務器和客戶端之間執行其他數據操作,並且它通常會作爲Json對象接收。包括這個例子。在我寫完if和做轉換之後,它開始大聲呼喊這個錯誤。在此之前,我只是做一個SQL查詢,獲取到一個數組,然後使用json_encode作爲'json'對象發送數據,它工作 – Lioo

0

嘗試使用JSON_FORCE_OBJECT代替JSON_PRETTY_PRINT

這樣的事情。

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

+0

嗨,我已經嘗試過,但它不起作用。它一直在喊同樣的錯誤 – Lioo

+0

你嘗試使用'dataType:'json','而不是'dataType:'jsonp',' – Archish

+0

是的,它給我一個跨域錯誤。這是一個跨域操作,那麼我必須使用jsonp。在這種情況下json不起作用 – Lioo

相關問題