2015-06-10 36 views
1

我有一個表格,我正試圖處理與React。這是handleSubmit功能的AJAX方法:Ajax成功問題與React和Rails

$.ajax({ 
    data: formData, 
    dataType: "json", 
    url: '/requests', 
    type: "POST", 
    success: function(data, status, xhr) { 
    console.log('SHOW HERE ON RESPONSE'); 
    this.setState({ 
     formSubmitted: true 
    }); 
    } 
}); 

當我點擊提交,我可以看到POST請求經過服務器用了200元。但成功回調從未進入過,我不迴應看到控制檯消息。

我的軌控制器的行動僅僅是一個簡單的:

return render nothing: true, status: 200 if request.xhr? 

與服務器響應日誌包括:

Completed 200 OK in 11ms (Views: 2.5ms | ActiveRecord: 2.6ms) 

然而,當我從成功回調Ajax請求移動的東西一個complete回調然後我看到在控制檯中的這個錯誤:

Uncaught TypeError: this.setState is not a function 

回答

2

你看到這個錯誤,因爲this$.ajax()success回調中行爲不同,因爲jQuery在內部使用它。

假設你正在執行以下ajax呼叫響應點擊功能,則:

var $this = $(this); 
$.ajax({ 
    data: formData, 
    dataType: "json", 
    url: '/requests', 
    type: "POST", 
    success: function(data, status, xhr) { 
    console.log('SHOW HERE ON RESPONSE'); 
     $this.setState({ 
     formSubmitted: true 
    }); 
    } 
}); 
2

在回調,this指的不是你所期望的背景下Ajax調用的jqXHR對象,(在這種情況下,您打電話給setState的組件)。

$.ajax允許您顯式設置上下文以避免這些類型的衝突。

$.ajax({ 
    data: formData, 
    dataType: "json", 
    url: '/requests', 
    type: "POST", 
    context: this, 
    success: function(data, status, xhr) { 
    console.log('SHOW HERE ON RESPONSE'); 
    this.setState({ 
     formSubmitted: true 
    }); 
    } 
}); 

添加context: this將解決這個問題。