PHP读取JSON-POST-Request并将其发回

时间:2013-04-19 14:23:33

标签: php jquery json post

我尝试使用PHP来读取JSON-POST-Request,但是我收到以下错误。

  

请求失败:parsererror

这是我的代码

    <script type="text/javascript" charset="utf-8" src="resources/js/model/Product.js"></script>
<script>
    function getdetails(){

        var p = new Product(15,11.5,"Pizza Test","P");
        var z = new Product(68,1.5,"Zutate Test","Z");

        p.addOneProduct(z);

        var request = $.ajax({
            type: "POST",
            url: "yb_test_post.php",
            dataType: "json",
            data: JSON.stringify(p)
        });

        request.done(function(msg) {
            $("#msg").html( " Post parameter are: <br/>"+msg );
        });

        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    }
</script>

和我的PHP代码,我尝试读取POST请求并立即打印

    <table>
<?php


    foreach ($_POST as $key => $value) {
        echo "<tr>";
        echo "<td>";
        echo $key;
        echo "</td>";
        echo "<td>";
        echo $value;
        echo "</td>";
        echo "</tr>";
    }


?>
</table>

我错了什么?

Product.js

function Product(id, price, name, type){
    this.id = id;
    this.price = +price;
    this.totalPrice = +price;
    this.name = name;
    this.type = type;
    this.products = [];
    var self = this;

    this.addOneProduct = function(oneProduct){
        self.products.push(oneProduct);
        self.totalPrice= self.totalPrice+oneProduct.price;
    };
}

1 个答案:

答案 0 :(得分:1)

你在做data: JSON.stringify(p)。这是发送一个JSON字符串作为帖子正文。你不想要这个。 PHP不会自动为您解析此问题。您希望向PHP发送一个查询字符串,这将使PHP自动将其解析为$_POST数组。

丢失JSON.stringify,试试这个:data: p

此外,dataType: "json" 响应 Content-type,而不是 请求 。您的PHP正在发回HTML,因此您需要:dataType: "html"

var request = $.ajax({
    type: "POST",
    url: "yb_test_post.php",
    dataType: "html",
    data: p
});