[英]Can not send a POST-JSON-Request with JavaScript
我嘗試用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;
};
}
我究竟做錯了什么?
你應該改變你的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)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.