gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:24:59 25 4
gpt4 key购买 nike

(抱歉我的英语)

我有一个小问题。


购物篮

我想在 session 中存储一个购物篮,所以我创建了 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 显示 Basket 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();

这将生成一个 JSON 对象,您可以将其与 jQuery .getJSON() 方法一起使用。

如下例所示(文件名: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>

关于javascript - 将对象的数组属性发送到 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com