2016-08-18 17 views
1

任何人都可以解釋爲什麼我的@model變量在我的ajax調用中不可用嗎? 當我嘗試在我的錯誤回調中使用@model變量時,它不存在。ajax調用內部不可用的變量

$.ajax URL+ "/api/v1/menu_items/#{@model.id}/verify", 
    type: 'PUT' 
    data: formData 

    error: (response) -> 
     alert(response) 
     window.location.href = "/menu_items/#{@model.id}" 
    success: (data) -> 
     window.location.href = "/menu_items/#{data.id}"  
+0

閱讀關於['.ajax'](http://api.jquery.com/jQuery.ajax/)並在回調中找到'this'的用法。然後可能使用'(response)=>'來使用綁定函數。 –

回答

0

使用=> fat arrow當你想在一個函數定義的外部範圍保持this

查看下面的評論。

$.ajax URL+ "/api/v1/menu_items/#{@model.id}/verify", 
    type: 'PUT' 
    data: formData 

    # this reference to the `this' where $.ajax is called. 

    error: (response) => # a function definition here. use => to bind this to the outer scope 
     alert(response) 
     window.location.href = "/menu_items/#{@model.id}" 
    success: (data) -> 
     # in this function, this will be bound to the object on which the success callback is called, normally, null 
     window.location.href = "/menu_items/#{data.id}"