简体   繁体   English

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

[英]Can not send a POST-JSON-Request with JavaScript

i try to send a POST-JSON-Request with jQuery 1.9. 我尝试用jQuery 1.9发送POST-JSON-Request。

I always get the following error in Console. 我总是在控制台中收到以下错误。

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

here is my code 这是我的代码

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

and Product.js 和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;
    };
  }

What am I doing wrong? 我究竟做错了什么?

You should alter your product.js The problem is that you're losing the reference to this . 你应该改变你的product.js的问题是,你失去了参照this

This should do the trick: 这应该做的伎俩:

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

EDIT: When you call the method addOneProduct, the this-reference is correctly resolved. 编辑:当您调用方法addOneProduct时,正确解析this-reference。 The problem is when actually try to call the service and set p as the data. 问题是当实际尝试调用服务并将p设置为数据时。 Upon serializing the object, JS actually calls into the method and at that point the reference is incorrect. 序列化对象后,JS实际调用了方法,此时引用不正确。 What you need to do is stringify the object before assigning it to the data: 您需要做的是在将对象分配给数据之前对其进行字符串化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM