2016-08-18 5 views
1

私の@model変数が私のajaxコールの中で利用できない理由を誰でも説明できますか? エラーコールバックの中で@model変数を使用しようとすると、存在しません。あなたが関数定義の外側のスコープでthisを保持したいとき変数は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を使用してください。

以下のコメントを確認してください。

$.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}" 
関連する問題