2015-01-26 52 views
1

我只是不知道如何在ajax成功中調用另一個聚合函數。聚合物!在Ajax成功中調用函數

這是我的代碼:

<script> 
    (function() { 
     // these variables are shared by all instances of app-globals 
     var firstName = "John"; 

     function setData(data) { 
      firstName = data; 
      console.log("Data gesetzt:" + firstName); 
     } 

     Polymer({ 
      ready: function() { 
       this.setTest("Example"); //Works 
       $.ajax({ 
        async: false, 
        type: "GET", 
        url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from, 
        dataType: 'jsonp', 
        error: function() { 
         alert('Unable to load feed, Incorrect path or invalid feed'); 
        }, 
        success: function (data) { 
         this.setTest(); //Doesnt work 
        } 
       }); 

      }, 
      setTest: function() { 
       console.log("hi"); 
      } 
     }); 
    })(); 
</script> 

那從成功的功能控制檯日誌:遺漏的類型錯誤:未定義是不是一個函數。

那麼如何在我的回調中調用setTest:function(){}?

回答

4

你需要讓this在成功處理程序具有正確的值(它通常會指向jqXHR對象)上下文選項jQuery的AJAX調用設置:

Polymer({ 
     ready: function() { 
      this.setTest("Example"); //Works 
      $.ajax({ 
       // set the context option so this will have the desired value 
       // in the success handler 
       context: this, 
       async: false, 
       type: "GET", 
       url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from, 
       dataType: 'jsonp', 
       error: function() { 
        alert('Unable to load feed, Incorrect path or invalid feed'); 
       }, 
       success: function (data) { 
        this.setTest(); // should work now 
       } 
      }); 

     }, 
     setTest: function() { 
      console.log("hi"); 
     } 

或者交替,你可以將this像這樣的值保存到另一個變量中,然後可以從回調中使用:

Polymer({ 
     ready: function() { 
      // save this value into another variable so it can be used in callbacks 
      var self = this; 
      this.setTest("Example"); //Works 
      $.ajax({ 
       async: false, 
       type: "GET", 
       url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from, 
       dataType: 'jsonp', 
       error: function() { 
        alert('Unable to load feed, Incorrect path or invalid feed'); 
       }, 
       success: function (data) { 
        self.setTest(); // should work now 
       } 
      }); 

     }, 
     setTest: function() { 
      console.log("hi"); 
     } 
+0

哇,謝謝你。很簡單!^^ – 2015-01-26 18:44:47