次のようにデータを投稿しようとするjQueryスクリプトがあります。
$.post({
$('div#location_select').data('cities-path'),
{ location_string: $('input#city_name').val() },
});
これは機能しますが、何らかの理由でサーバーはそれを JS リクエストではなく HTML リクエストとして受け取ります。何を与える?コントローラーの応答ブロックは次のとおりです。
if @city.save
respond_to do |format|
format.html { redirect_to @city }
format.json { render :json => @city, :status => :ok }
end
else
respond_to do |format|
format.html { render :new }
format.json { render :json => { :error => "Incorrect location format, please input a city and state or country, separated by a comma." }, :status => :unprocessable_entity }
end
end
format.js
Ajax リクエストがコントローラーにヒットし、レスポンダーによって処理されるようにするにはどうすればよいでしょうか?
更新:データ型をから に変更し$.post
て具体的に定義すると、次のように機能します。$.ajax
$.ajax({
type: 'POST',
url: $('div#location_select').data('cities-path'),
data: { location_string: $('input#city_name').val() },
dataType: 'json'
});