无法使用JavaScript发送POST-JSON-Request

时间:2013-04-19 13:54:18

标签: javascript jquery json post request

我尝试使用jQuery 1.9发送POST-JSON-Request。

我总是在控制台中收到以下错误。

  

TypeError:this.products未定义。 this.products.push(oneProduct);

这是我的代码

<script src="http://code.jquery.com/jquery-latest.js"></script>
<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: p
        });

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

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

和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 = [];

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

我做错了什么?

1 个答案:

答案 0 :(得分:4)

您应该更改您的product.js问题是您丢失了对this的引用。

这应该可以解决问题:

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;
    };
  }

编辑:调用方法addOneProduct时,正确解析了this-reference。问题是当实际尝试调用服务并将p设置为数据时。序列化对象后,JS实际调用了方法,此时引用不正确。您需要做的是在将对象分配给数据之前对其进行字符串化:

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