簡體   English   中英

將對象的數組屬性發送到Ajax

[英]Sending array attribute of object to Ajax

對不起,我的英語

我有一點問題。


商店籃

我想在會話中存儲購物籃,因此我創建了php/classes/bascket.php

class Product
{
    private $id;
    private $quantity;

    function __construct(int $id, int $q)
    {
        $this->id = $id;
        $this->quantity = $q;
    }

    ...
}

class Bascket
{
    private $products = array();

    /* for testing */
    function __construct()
    {
        $this->products[] = new Product(26, 1006);
    }

    function add(int $id, int $quantity)
    {
        ...
    }

    function delete(int $id, int $quantity)
    {
        ...
    }

    function __get($field) {
        return $this->$field;
    }
}


使用購物籃

我可以在任何需要的會話上使用此類:

include "php/classes/bascket.php"; (*or another correct path*)

session_start();

if(!isset($_SESSION["bascket"])) {
    $_SESSION["bascket"] = serialize(new Bascket());
}
$bascket = unserialize($_SESSION["bascket"]);


試圖與Ajax一起展示Bascket Shop

因為我想在按下按鈕時顯示籃筐,所以我制作了一個ajax,它可以執行以下操作:

function display_bascket() {
    $.ajax({
        url: 'php/take_bascket.php',
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,                         
        type: 'post',
        success: function(bascket){
           //bascket = JSON.parse(bascket);
           //bascket = jQuery.parseJSON(bascket);
           $("#content").html(bascket);
        }
   });
}

我做了很多嘗試,以便可以在take_bascket.php顯示正確的內容,以接收一個好的數組或ajax中的json。


take_bascket.php

<?php

session_start();

include "classes/bascket.php";

if(!isset($_SESSION["bascket"])) {
    $_SESSION["bascket"] = serialize(new Bascket());
}

// I tried many variants:


var_dump($_SESSION["bascket"]);
/*
 * output:
 * string(116) "O:3:"Bascket":1:{s:12:"Bascketproducts";a:1:{i:0;O:6:"Product":2:{s:10:"Productid";i:26;s:17:"Productquantity";i:1006;}}}"
 *
 * and I don't know how to handled it in ajax to get the products array
*/

var_dump(unserialize($_SESSION["bascket"]));
/*
 * output:
 * object(Bascket)#1 (1) { ["products":"Bascket":private]=> array(1) { [0]=> object(Product)#2 (2) { ["id":"Product":private]=> int(26) ["quantity":"Product":private]=> int(1006) } } }
 *
 * and I don't know how to handled it in ajax to get the products array
*/

var_dump(json_encode($_SESSION["bascket"]));
/*
 * output:
 * string(158) ""O:3:\"Cos\":1:{s:12:\"\u0000Cos\u0000products\";a:1:{i:0;O:6:\"Product\":2:{s:10:\"\u0000Product\u0000id\";i:26;s:17:\"\u0000Product\u0000quantity\";i:1006;}}}""
 *
 * and I don't know how to handled it in ajax to get the products array
*/

var_dump(((unserialize($_SESSION["bascket"]))->products));
/*
 * output:
 * array(1) { [0]=> object(Product)#2 (2) { ["id":"Product":private]=> int(26) ["quantity":"Product":private]=> int(1006) } }
 *
 * and I don't know how to handled it in ajax to get the products array
*/

var_dump(((unserialize($_SESSION["bascket"]))->products[0]));
/*
 * output:
 * object(Product)#2 (2) { ["id":"Product":private]=> int(26) ["quantity":"Product":private]=> int(1006) }
 *
 * and I don't know how to handled it in ajax to get the products array
*/


結論

如您所見,我還嘗試了不同的方式來操縱ajax中的輸出。 但是,或者它是一個字符串,我無法將其轉換為數組。 或者我無法將其設為json等。


請,您可以嘗試找到完整的解決方案嗎? 我的意思是對於take_bascket.php,但也指我在js的display_bascket()中要做的事情。
先感謝您


編輯

我按照某人在帖子中所說的那樣做:
php/classes/bascket.php

<?php

class Product
{
    private $id;
    private $quantity;

    function __construct(int $id, int $q)
    {
        $this->id = $id;
        $this->quantity = $q;
    }

    function decrease(int $value)
    {
        ...
    }

    function increase(int $value) {
        ...
    }

    public function toArray(){
        return [
            'id' => $this->id,
            'quantity' => $this->quantity,
        ];
    }
}

class Bascket
{
    private $products = array();

    /* for testing */
    function __construct()
    {
        $this->products[] = new Product(26, 1006);
    }

    function add(int $id, int $quantity)
    {
        ...
    }

    function delete(int $id, int $quantity) 
    {
        ...
    }

    public function toJson(){
        $products = [];
        foreach ($this->products as $product) {
            $products[] = $product->toArray();
        }
        return json_encode(
            [
                'products' => $products
            ],
            JSON_PRETTY_PRINT
        );
    }

    function __get($field) {
        return $this->$field;
    }
}

從理論上講,這就是我更輕松地創建PHP JSON的方式。
但是看看take_bascket.php

<?php

session_start();

include "classes/bascket.php";

if(!isset($_SESSION["bascket"])) {
    $_SESSION["bascket"] = serialize(new Bascket());
}

var_dump(((unserialize($_SESSION["bascket"]))->toJson()));
/*
 * output:
 * string(98) "{ "products": [ { "id": 26, "quantity": 1006 } ] }" 
*/


嘗試在display_bascket()使用它:

function display_bascket() {
    $.ajax({
        url: 'php/take_bascket.php',
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,                         
        type: 'post',
        success: function(bascket){
           //bascket = JSON.parse(bascket);
           $("#content").html(bascket);
        }
   });
}

如果我不使用JSON.parse() ,它將顯示下一個純文本:
string(98)“ {”產品“:[{” id“:26,”數量“:1006}]}”

相反,如果我使用JSON.parse(),則會出現控制台錯誤:

Uncaught SyntaxError: Unexpected token s in JSON at position 0 
at JSON.parse (<anonymous>)at Object.success (display_bascket.js:10) 
at j (jquery.js:2) at Object.fireWith [as resolveWith] (jquery.js:2) 
at x (jquery.js:4) at XMLHttpRequest.b (jquery.js:4)


我該怎么辦?

我建議在每個對象中創建一個方法,該方法將返回該對象的JSON表示形式。

例如(文件名:products.php):

class Product {

    private $name;
    private $value;
    private $quantity;

    public function __construct($name, $value, $quantity){
        $this->name = $name;
        $this->value = $value;
        $this->quantity = $quantity;
    }

    public function toArray(){
        return [
            'name' => $this->name,
            'value' => $this->value,
            'quantity' => $this->quantity,
        ];
    }
}

class Basket{

    private $products = [];

    public function addProduct(Product $p){
        $this->products[] = $p; 
    }
    public function toJson(){
        $products = [];
        foreach ($this->products as $p) {
            $products[] = $p->toArray();
        }
        return json_encode(
            [
                'products' => $products
            ],
            JSON_PRETTY_PRINT
        );
    }
}

$b = new Basket();

$b->addProduct(new Product('Apple', 1, 5));
$b->addProduct(new Product('Banana', .5, 2));
$b->addProduct(new Product('Carrots', .35, 6));

echo $b->toJson();

這將生成一個可與jQuery .getJSON()方法一起使用的JSON對象。

類似於下面的示例(文件名:products.html):

<html>
    <head>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
    </head>
    <body>
        <h3>Product list</h3>
    </body>
    <script>
        $(function(){
            $.getJSON( "products.php", function( data ) {
                console.log(data);
                var items = [];
                $.each( data.products, function( key, val ) {
                  items.push( "<li>Name: " + val.name + " | Quantity: " + val.quantity + " | Price: " + val.value + "</li>" );
                });

                $( "<ul/>", {
                  html: items.join( "" )
                }).appendTo( "body" );
            });
        });
    </script>
</html>

暫無
暫無

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

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