2017-02-19 83 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()与关联数组而不是对象进行解码。