2013-04-19 4 views
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; 
    }; 
    } 

?

답변

4

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를 호출 할 때는이 참조가 제대로 해결됩니다. 문제는 실제로 서비스를 호출하고 p를 데이터로 설정하려고 할 때입니다. 객체를 직렬화하면 JS는 실제로 메소드를 호출하고 그 시점에서 참조가 올바르지 않습니다. 데이터를 객체에 할당하기 전에 객체를 문자열로 변환해야합니다.

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

'this'에 대한 참조를 어떻게 잃어 버리십니까? 'p.'와 같이 호출하면 참조를 잃지 않습니다. – Ian

+0

을 시도했지만 이제는 다른 오류가 발생합니다. TypeError : oneProduct는 정의되지 않았습니다. self.totalPrice = self.totalPrice + oneProduct.price; – user1167253

+0

'addOneProduct'는'this'에 바인드 된 메소드이므로, 함수를 메소드로 호출하는 한'this'는 잃어서는 안됩니다. - http://jsfiddle.net/Kq6Jw/. 만약 당신이'var a = p.addOneProduct;(); ' – Ian

관련 문제