【问题标题】:Can not send a POST-JSON-Request with JavaScript无法使用 JavaScript 发送 POST-JSON-Request
【发布时间】:2013-04-19 13:54:18
【问题描述】:

我尝试使用 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;
    };
  }

我做错了什么?

【问题讨论】:

    标签: javascript jquery json post request


    【解决方案1】:

    您应该更改您的 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)
            });
    

    【讨论】:

    • 如何丢失对this 的引用?当您像p. 一样调用它时,它不会丢失引用
    • 我已经尝试过,但现在又收到另一个错误 TypeError: oneProduct is undefined self.totalPrice= self.totalPrice+oneProduct.price;
    • addOneProduct是绑定到this的方法,所以只要将函数作为方法调用,this就不会丢失。 -jsfiddle.net/Kq6Jw。如果你做了var a = p.addOneProduct; a();,那就不一样了
    • 你说得对,我没看到。我为疏忽道歉
    • @user1167253 您的代码运行良好 - jsfiddle.net/Kq6Jw/1。您确定您也没有在其他地方使用此代码吗?或者你确定错误是指p.addOneProduct(z);这一行?
    猜你喜欢
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 2011-11-11
    相关资源
    最近更新 更多