我瞭解ajax如何與Rails一起工作。我有一個方法,取決於在html選擇中選擇了什麼選項,我用第一個選擇的值加載另一個選擇。如果重要,這些選擇在_partial中。當我使用GET並且響應爲「錯誤字符串:SyntaxError:意外的令牌<。Status:parsererror」時,我無法讓控制器打印我的任何'puts'語句。但後來奇蹟般地把它改成POST後一切正常。爲什麼ajax POST工作,但GET不與Rails json請求
這裏是路線:
get '/mycontroller/get_list_with_ajax'
JS:
$.ajax({
url: "/mycontroller/get_list_with_ajax",
data: {
"groupName": groupName,
"authenticity_token": $('meta[name="csrf-token"]').attr('content')
},
type: "GET",
dataType: "json",
timeout: constants.AJAX_TIMEOUT,
cache: false,
success:function(result) {
...
控制器:
def get_list_with_ajax
puts "HELLO!"
...
result = { 'response' => 'SUCCESS',
'more_options' => ['example'] }
render :json => result
end
編輯:我注意到當我使用POST響應內容類型是「應用/ json'和GET將它設置爲'text/html。我已經嘗試了全部3種:
response.headers["Content-Type"] = "application/json"
response.content_type = 'application/json'
render :json => result, :content_type => 'application/json'
但是它們都沒有改變Chrome控制檯或curl -LI的結果。不知道爲什麼。
如果有人能指出我正確的方向,將不勝感激,謝謝。
嘗試添加'頭:{「內容類型:應用程序/ JSON」}'型後':「 GET「,' –
@RailsOuter hmm no dice。控制檯不斷抱怨:主線程上的同步XMLHttpRequest已被棄用,因爲它對最終用戶的體驗有不利影響。如需更多幫助,請查看http://xhr.sp ec.whatwg.org/。 – Tim
嘗試用{「Accept」:「application/json」}獲取請求。 –