У меня есть Rails API, который работает с CURL, но не с $ .ajax. Вот метод контроллера, который делает API:Использование jQuery ajax для запроса Rails API на localhost
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 -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)
EDIT: Вот код #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>
EDIT 2: Му прав, у меня был дополнительный -> в моем 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")
Спасибо за помощь.
@muistooshort - Я добавил код для элемента #return_calculator_button. Благодарю. – Powers
, пожалуйста, вы можете поместить здесь результирующий js (источник кода в браузере). Я думаю, что это плохое решение для преобразования CoffeeScript. – Aguardientico
@muistooshort - Спасибо за помощь. Я использовал ваши ответы на кучу других вопросов StackOverflow и очень ценю, насколько вы вносите свой вклад в сообщество: D – Powers