$ .ajax가 아니라 CURL로 작업하는 Rails API가 있습니다.jQuery ajax를 사용하여 로컬 호스트에서 Rails API에 요청하기
여기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'
는 버튼이 클릭되었을 때 실행된다는 커피 스크립트이다 :
여기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 요청은 : 여기 API하게 컨트롤러 방법은
$ = 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의 헤더 나는 다음과 같은 오류 얻을 $ 아약스 호출에 포함되는 경우 :
에게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)
편집 : contentType의 헤더가 나는 다음과 같은 오류 얻을 $ 아약스 호출에 포함되지 않은 691,363,210
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)
여기 는 #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")
감사합니다.
@muistooshort는 - 나는 #return_calculator_button 요소에 대한 코드를 추가했다. 감사. – Powers
여기에 결과 js (브라우저의 코드 소스)를 넣을 수 있습니까? 커피 스크립트 변환 문제가 나쁜 것 같아요. – Aguardientico
@muistooshort - 도와 줘서 고마워. 다른 StackOverflow 질문에 대한 답변을 사용했으며 커뮤니티에 얼마나 기여했는지 정말 고맙게 생각합니다. D – Powers