输入商品数量并单击">添加到购物车"按钮后,将执行toShoppingCart()
方法。此方法将获取标签和文本字段的值,并将它们插入到 JSON 对象中并将其传递给Order.php
文件。
将 JSON 对象从 JavaScript 发送到 PHP 时,它会返回一个错误:
Undefined index: itemdetails
Onearlist.html
:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Order.php">
<table border="2">
<tr>
<td>
<div style="padding: 40px"><label id="id">001</label> <label id="name">SMS Audio street by 50 on-ear wired</label> <label id="price">179.00$</label> Qty <input type="text" id="qtytxt"><input type="button" value="Add to Cart" onclick="toShoppingCart()" /></div>
</td>
</tr>
<tr>
<td>
<div style="padding: 40px"><label id="id">002</label><label id="name">Beats Solo2 on-ear wired</label> ,<label id="price">199.00$</label> Qty<input type="text" id="qtytxt"><input type="button" value="Add to Cart" onclick="toShoppingCart()" /></div>
</td>
</tr>
<tr>
<td>
<div style="padding: 60px"></div>
</td>
</tr>
</table>
<input type="submit" value="Check Out">
</form>
<script type="text/javascript">
function toShoppingCart() {
console.log("toShoppingCart");
var id = document.getElementById("id").innerHTML;
var name = document.getElementById("name").innerHTML;
var qty = document.getElementById("qtytxt").value;
var price = parseFloat(document.getElementById("price").innerHTML);
console.log(id);
console.log(name);
console.log(qty);
console.log(price);
var request;
var itemdata = {
"id": id,
"name": name,
"qty": qty,
"price": price
};
open("Order.php", "window1");
send({
itemdetails: JSON.stringify(itemdata)
});
}
</script>
</body>
</html>
Order.php
:
<?php
$data = json_decode($_GET['itemdetails']);
echo $data;
?>
要发送 ajax 请求,请执行以下操作:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(request.responseText); // get response form the server
}
};
request.open('GET', 'Order.php?itemdetails='+JSON.stringify(itemdata), true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.send(null);
或者如果你使用 jQuery,那么:
$.get('Order.php?itemdetails='+JSON.stringify(itemdata), function(response) {
});