使用 jQuery POST 函数从服务器返回 JSON 数据

Aaj*_*jiz 3 ajax jquery post json get

我正在尝试从 PHP 脚本返回一个 json 编码的字符串。

$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
    $("#price").html("$" + data.price);
    $("#discount").html("$" + data.discount);
    $("#total").html("$" + data.total);
});
Run Code Online (Sandbox Code Playgroud)

我尝试在回调中使用警报函数来查看 PHP 的返回值:

{"price":249,"discount":"0.00","total":249}
Run Code Online (Sandbox Code Playgroud)

但是#price 和rest 元素的值是“$undefined”。

请帮忙。

Sir*_*rko 5

看来您只需要使用parseJSON()以下方法将 JSON 数据解析为一个对象:

$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
    data = $.parseJSON( data );
    $("#price").html("$" + data.price);
    $("#discount").html("$" + data.discount);
    $("#total").html("$" + data.total);
});
Run Code Online (Sandbox Code Playgroud)