這個問題上有很多,但我不明白爲什麼它不工作,它現在停止了。我運行查詢並返回一個對象與PHP,然後嘗試將其編碼到JSON,然後解析它的客戶端到JSON。它告訴我,SyntaxError:JSON.parse:JSON數據後的意外的非空白字符。將php對象編碼爲json
我的PHP代碼:
$product = ShoppingCart::addToCart($_GET['product_id']);
echo json_encode($product);
客戶端代碼:
$.get(
'./models/shoppingCart.inc.php',
{product_id: id},
function(data) {
var product = JSON.parse(data)
$('#cart_qty').html(cartQty);
var table=document.getElementById("table_products");
var row=table.insertRow(1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML=product.product_name;
cell2.innerHTML=product.price;
cell3.innerHTML=qty;
},
'html'
);
};
這是被退回了什麼:
16{"product_id":"16","product_name":"Pavlova","price":"17.4500","supplier":{"company_name":"Pavlova, Ltd.","address":"74 Rose St.\r\nMoonie Ponds","phone":"(03) 444-2343","city":null,"contact_name":"Ian Devling","contact_title":"Marketing Manager"},"units_in_stock":"29","units_on_order":"0","reorder_level":"10","category_id":"3","qty_per_unit":"32 - 500 g boxes","discontinued":"0","supplier_id":"7"}
該腳本的其他部分在您顯示的PHP代碼之前回顯'16'。 – Barmar
你在做'echo $ _GET ['product_id'];'在你調用'echo json_encode($ product);'某處? – MonkeyZeus