2016-06-07 4 views
-4

데이터와 함께 일부 작업을 수행 한 PHP 파일이 있는데 json 형식 (추정 됨)으로 데이터를 보냅니다.Json_encode가 객체 대신 문자열을 반환합니다.

그런 다음 jax 파일을 사용하여 ajax를 사용하여 데이터를 수신합니다. 그것은 크로스 도메인 작업입니다, 그렇다면 jsonp를 사용해야합니다.

문제는 내가 내가 JSONP에서 데이터 유형을 변경할 때 내가 (간단한 문자열을 JSON 객체로하지만, 같은 데이터를받을 수없는 때문이라고 생각하는 오류

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

를 받고있어 것입니다 텍스트는 .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).')'; 


} 

이 편집 : 나는 자바 스크립트 코드를 게시하는 것을 잊었다 , 여기 간다 :

코드 :

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

당신은뿐만 아니라 자바 스크립트를 게시해야합니다. – 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은 문자열 일뿐입니다. 자바 스크립트에서 json 문자열을 객체로 변환하려면 jQuery를 사용하는 경우 자바 스크립트에서 $ .parseJSON을 사용하십시오.

+0

예, 알지만, json_encode를 사용하여 서버와 클라이언트간에 다른 작업을 수행해야하며 정상적으로 Json 객체로 수신했습니다. 이 예제를 포함합니다. 내가 if를 작성하고 전환을 수행 한 직후에이 오류를 소리 치기 시작했습니다. 그 전에는 SQL 쿼리를 수행하여 배열로 가져온 다음 json_encode를 사용하여 데이터를 'json'객체로 보내고 작동했습니다. – Lioo

0

대신 JSON_PRETTY_PRINT을 사용해보세요.

이와 비슷한 내용입니다.

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

+0

안녕하세요, 이미 시도했지만 작동하지 않았습니다. – Lioo

+0

'dataType : 'json','jsonp ',' – Archish

+0

'대신'dataType : 'json','을 사용하려고 했는가? 그렇다. 크로스 도메인 오류가 발생한다. 그것은 크로스 도메인 작업이고, 그렇다면 jsonp를 사용해야합니다. json이이 상황에서 나를 위해 작동하지 않습니다 .htaccess의 – Lioo

관련 문제