将对象的数组属性发送到Ajax

时间:2017-09-22 19:19:45

标签: javascript php jquery json ajax

对不起我的英语

我有点问题。


Shop Bascket

我想在会话中存储一个shop-bascket,所以我创建了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;
    }
}


使用Shop Bascket

我在会话的任何地方使用这个课程:

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)“{”products“:[{”id“:26,”quantity“: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)


我该怎么办?

1 个答案:

答案 0 :(得分:1)

我建议在每个对象中创建一个返回该对象的JSON表示的方法。

例如(filename:products.php):

cosine = (double (*)(double))dlsym(handle, "cos")

这将生成一个可以与jQuery 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(); 方法一起使用的JSON对象。

如下面的示例(filename:products.html):

.getJSON()