1
jQuery 1.9를 사용하여 POST-JSON 요청을 보내려고합니다.JavaScript로 POST-JSON 요청을 보낼 수 없습니다.
콘솔에서 항상 다음 오류가 발생합니다. 여기
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;
};
}
?
'this'에 대한 참조를 어떻게 잃어 버리십니까? 'p.'와 같이 호출하면 참조를 잃지 않습니다. – Ian
을 시도했지만 이제는 다른 오류가 발생합니다. TypeError : oneProduct는 정의되지 않았습니다. self.totalPrice = self.totalPrice + oneProduct.price; – user1167253
'addOneProduct'는'this'에 바인드 된 메소드이므로, 함수를 메소드로 호출하는 한'this'는 잃어서는 안됩니다. - http://jsfiddle.net/Kq6Jw/. 만약 당신이'var a = p.addOneProduct;(); ' – Ian