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

标签 javascript jquery json post request

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

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

TypeError: this.products is undefined. 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;
    };
  }

我做错了什么?

最佳答案

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

关于javascript - 无法使用 JavaScript 发送 POST-JSON-Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16106296/

相关文章:

xml - SSAS 多维数据集的 JSON 结果

javascript - 使用 axios 在 POST 多部分/表单数据请求中发送文件和 json

python - pretty-print JSON

javascript - JQuery .hover/.on ('mouseleave' ) 无法正常运行

javascript - 在javascript延迟后更改图像

javascript - 添加基于php数据库结果的表单确认

javascript - PHP 表自动更新数据但不更新表

javascript - HTML 变量和文本值传输到 PHP/javascript?

javascript - AngularJS 组件 - 带有 Typescript 的 ngModelController

javascript - 使用 ASP.NET 和 C# 将文件上传到服务器