1

CURL で動作する Rails API がありますが、$.ajax では動作しません。API を作成するコントローラー メソッドは次のとおりです。

  def historic_returns
    start_date = Date.new(params[:start_year].to_i, params[:start_month].to_i)
    end_date = Date.new(params[:end_year].to_i, params[:end_month].to_i)

    @result = ShillerDataMonth.records_between_two_dates(start_date, end_date)

    respond_to do |format|
      format.json { render :json => @result }
    end
  end

期待される出力を返す CURL リクエストは次のとおりです。

curl -H 'Content-type: application/json' -H 'Accept: application/json' -d '{"start_year":"2008","start_month":"1","end_year":"2008","end_month":"12"}' 'http://localhost:3000/historic_returns.json'

ボタンがクリックされたときに実行される CoffeeScript は次のとおりです。

$ = jQuery

$ ->
  $('#return_calculator_button').click ->
    $.ajax ->
      url: "http://localhost:3000/historic_returns.json"
      contentType: "application/json"
      type: "GET"
      data: {"start_year":"2008","start_month":"1","end_year":"2008","end_month":"12"}
      dataType: "json"
      success: (data) ->
        alert("success #{data}")
      error: ->
        alert("failure")

contentType ヘッダーが $.ajax 呼び出しに含まれている場合、次のエラーが発生します。

GET http://localhost:3000/function%20()%20%7B%20%20%20%20%20%20%20%20return%20%…0%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%7D;%20%20%20%20%20%20%7D 400 (Bad Request) 

contentType ヘッダーが $.ajax 呼び出しに含まれていない場合、次のエラーが発生します。

GET http://localhost:3000/function%20()%20%7B%20%20%20%20%20%20%20%20return%20%…0%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%7D;%20%20%20%20%20%20%7D 404 (Not Found)

編集: #return_calculator_button のコードは次のとおりです。

<div class="control-group">
  <div class="controls">
    <button type="button" class="btn btn-primary" id="return_calculator_button">Calculate the Return</button>
  </div>
</div>

編集 2: Mu は正しいです。CoffeeScript に余分な -> がありました。正しいコードは次のとおりです。

$ = jQuery

$ ->
  $('#return_calculator_button').click ->
    $.ajax
      url: "http://localhost:3000/historic_returns.json"
      #contentType: "application/json"
      type: "GET"
      data: {"start_year":"2008","start_month":"1","end_year":"2008","end_month":"12"}
      dataType: "json"
      success: (data) ->
        alert("success #{data}")
        console.log data
      error: ->
        alert("failure")

助けてくれてありがとう。

4

1 に答える 1

1

関数を渡し$.ajaxています:

$.ajax ->
# -----^^

その関数はたまたま、$.ajax通常取得する通常のオプション オブジェクトを返しますが、これは付随的なものです。その結果、通常のフォームではなくフォーム$.ajaxを使用していると見なされます。したがって、関数は URL であり、ログの混乱は文字列化された関数を URL エンコードした結果であると考えられます。$.ajax(url, [settings])$.ajax([settings])$.ajax

ドロップ->:

$.ajax
  url: "http://localhost:3000/historic_returns.json"
  # as you have now...
于 2013-07-02T02:43:00.073 に答える