代码之家  ›  专栏  ›  技术社区  ›  user1167253

无法使用JavaScript发送POST JSON请求

  •  1
  • user1167253  · 技术社区  · 12 年前

    我试图用jQuery 1.9发送一个POST JSON请求。

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

    类型错误: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>
    

    和产品.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 回复  |  直到 12 年前
        1
  •  4
  •   Kenneth    12 年前

    你应该修改你的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方法时,该引用将被正确解析。问题是当实际尝试调用服务并将p设置为数据时。在序列化对象时,JS实际上调用了该方法,此时引用是不正确的。您需要做的是在将对象分配给数据之前将其字符串化:

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