簡體   English   中英

php ajax未返回預期結果,可能是json解碼問題

[英]php ajax not returning expected result, possible json decode issue

將以下代碼粘貼到PHP中。

        $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}]

現在,遵循相同的邏輯。 在下面粘貼Java腳本

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框架

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

我希望上面的兩段代碼在控制台中顯示的內容與我的“預期結果”相似,但在控制台中什么也沒有顯示。 如果我將上面的代碼更改為以下代碼

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是無狀態的,因此我是否有辦法通過在控制台中回顯php頁面而不用json編碼的方式來解決ajax問題?

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()正在使用關聯數組而不是對象進行解碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM