2017-02-19 1 views
0

다음 코드를 PHP에 붙여 넣습니다.PHP 아약스가 예상 결과를 반환하지 않음, 가능한 json 디코딩 문제

 $json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]'; 
     $json2 = json_decode($json); 

     foreach($json2 as $item){ 
      $item->total = 9; 
     } 

     foreach($json2 as $item){ 
      print_r($item); 
      echo "<br>"; 
     } 

     echo json_encode($json2); 

위의 코드는 다음 결과를 표시합니다. 나는 이것을 "예상 결과"라고 부를 것이다.

stdClass Object ([id] => 1 [quantity] => 2 [total] => 9) 
stdClass Object ([id] => 1 [quantity] => 2 [total] => 9) 
stdClass Object ([id] => 1 [quantity] => 2 [total] => 9) 
[{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9}] 

지금, 동일한 논리를 따른다. 이

public function ajax_test(){ 
    $json = $this->input->post('json'); 
    $json2 = json_decode($json); 
    foreach($json2 as $item){ 
     $item->total = 2; 
    } 
    echo json_encode($json2); 
    } 

내가 같은 콘솔에서 비슷한 것을 보여주기 위해 위의 코드 2 조각을 예상하는 데 도움이 경우

function test(){ 
    var json = [{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]; 
    $.ajax({ 
      url: base_url+"Product/ajax_test", 
      type: "POST", 
      dataType: "JSON", 
      data: { 
        'json':json, 
       }, 
      success:function(data){ 
       console.log(data); 
      }//end success function 
     });//end of ajax 
} 

그리고 아래의 PHP를 붙여 아래에 붙여 넣기 자바 스크립트, 나는 CodeIgniter의 프레임 워크를 사용하고 내 "expected result"하지만 콘솔에 아무것도 표시되지 않습니다. 위 코드를 다음과 같이 변경하면

public function ajax_test(){ 
     $json = $this->input->post('json'); 

     foreach($json as $item){ 
      $item["total"] = 2; 
     } 
     echo json_encode($json); 
    } 

위 코드는 결과를 콘솔에 표시합니다. "total"속성은 단순히 원래의 $json 변수를 돌려 준 것처럼 최종 결과에 포함되지 않습니다. 그리고 이상한데 $item->total 대신 $item["total"]을 사용해야합니다.

질문 1, 위의 내용에서 내가 뭘 잘못 했습니까? 질문 2, PHP는 상태가 없으므로 json 인코딩을 사용하지 않고 콘솔에서 PHP 페이지를 반향 출력하여 ajax를 촬영하는 데 문제가 생길 수 있습니다.

+0

내 답변이 도움이 되었습니까? https://stackoverflow.com/help/someone-answers를 참조하십시오. – miken32

답변

0

json_decode()은 개체 또는 배열로 JSON 개체를 디코딩 할 수 있습니다. 우리는 당신이 그것을 제공하지 않기 때문에 알 수 없지만

$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]'; 
$json_with_objects = json_decode($json); 
$json_with_arrays = json_decode($json, true); 

echo $json_with_objects[0]->quantity; 
echo $json_with_arrays[0]["quantity"]; 

var_dump($json_with_objects); 
var_dump($json_with_arrays); 

아마도, 코드 $this->input->post()는 연관 배열 대신 객체로 디코딩한다.

관련 문제