1

次のようにデータを投稿しようとする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.jsAjax リクエストがコントローラーにヒットし、レスポンダーによって処理されるようにするにはどうすればよいでしょうか?


更新:データ型をから に変更し$.postて具体的に定義すると、次のように機能します。$.ajax

$.ajax({
  type: 'POST',
  url: $('div#location_select').data('cities-path'),
  data: { location_string: $('input#city_name').val() },
  dataType: 'json'
});
4

1 に答える 1

3

routes.rb のルートからフォーマットを渡していますか?

"controller/action/(.:format)"
于 2012-04-12T20:32:49.240 に答える