2017-02-19 77 views
0

將以下代碼粘貼到PHP中。php ajax沒有返回預期的結果,可能的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}] 

現在,遵循相同的邏輯。下面

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粘貼Java腳本,我使用笨框架的工作,如果這有助於

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的代碼顯示在控制檯類似的東西我「預期結果」,但沒有在控制檯中顯示。如果我將上面的代碼更改爲以下代碼

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

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

上面的代碼將在控制檯中顯示結果。 「總數」屬性並不是最終結果,好像它只是簡單地給出原始$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()與關聯數組而不是對象進行解碼。