2016-09-14 114 views
-1

我目前正在使用谷歌地圖,我想保存一些位置在數據庫中,並通過ajax調用檢索它們,之後我從位置創建JavaScript對象。從ajax成功調用運行javascript函數

至於代碼我不確定爲什麼這不起作用,有人可以爲我清除這個嗎?

Chrome的控制檯: 遺漏的類型錯誤:this.processData不是一個函數

var Locations = { 
 
    count: 0, 
 
    location: [], 
 
    processData: function (data) { 
 
     console.log(data); 
 
    }, 
 
    getData: function() { 
 
     'use strict'; 
 
     
 
     jQuery.ajax({ 
 
      type: 'get', 
 
      url: '../../php/functions/getLocations.function.php', 
 
      dataType: 'json', 
 
      success: function (data) { 
 
       this.processData(data); 
 
      } 
 
     }); 
 
    } 
 
};
關於評論凱文乙貼,當異步調用完成後右側做部分應該運行? 最後編輯:

function getLocation() { 
    return $.ajax({ 
     type: 'get', 
     url: '../../php/functions/getLocations.function.php', 
     dataType: 'json' 
    }); 
} 

getLocation().done(function(result) { 
    console.log(result); 
    return result; 
}); 
+0

我編輯這個職位有一個新的問題.. – Smoothal

+0

,它仍然是一個欺騙,但另一個問題:你不能從異步函數返回。那是不可能的。 –

+0

由於您的修改使現有答案無效,因此我將問題推回原位。如果你有新的問題,你應該把它作爲一個新的問題。然而,你要問的是一個非常受歡迎的笨蛋;你應該先搜索。 http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –

回答

1

關鍵字this是指它在初始化範圍 所以你的情況這是success - 函數的範圍。它不涉及對象本身。

爲了達到這個目的,你必須緩存對該對象的引用,以便在success函數內使用它或引用對象本身。

對象引用:

jQuery.ajax({ 
    type: 'get', 
    url: '/echo/json/', 
    dataType: 'json', 
    success: function(data) { 
    Locations.processData(data); 
    } 
}); 

緩存this

getData: function() { 
    'use strict'; 
    let _this = this; 
    jQuery.ajax({ 
     type: 'get', 
     url: '/echo/json/', 
     dataType: 'json', 
     success: function(data) { 
     _this.processData(data); 
     } 
    }); 
    } 

Fiddle

+0

答案几乎就在那裏....提供一個例子。 – Adam

+0

亞當是對的,但我明白了。我會嘗試去適應它 – Smoothal

+0

@平滑添加了2個具體的例子。我個人會和第二個一起去的。 – empiric

0

this指向AJAX設置對象。無論是使用$ .proxy或將其存儲在一個變量之後使用this讓你的目標正確context

getData: function() { 
     'use strict'; 
     var thisLocation = this; 
     jQuery.ajax({ 
      type: 'get', 
      url: '../../php/functions/getLocations.function.php', 
      dataType: 'json', 
      success: function (data) { 
       thisLocation.processData(data); 
+0

@KevinB - 回答者沒有提供代碼示例,但只是提到了這個事實,即當我發表評論 – Adam

+0

時這個錯誤是爲什麼沒用?這是正確的。 –

+0

答案目標已經存在。重複的答案 - >沒有用。 –