2013-07-02 2 views
1

$ .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") 

감사합니다.

+0

@muistooshort는 - 나는 #return_calculator_button 요소에 대한 코드를 추가했다. 감사. – Powers

+0

여기에 결과 js (브라우저의 코드 소스)를 넣을 수 있습니까? 커피 스크립트 변환 문제가 나쁜 것 같아요. – Aguardientico

+0

@muistooshort - 도와 줘서 고마워. 다른 StackOverflow 질문에 대한 답변을 사용했으며 커뮤니티에 얼마나 기여했는지 정말 고맙게 생각합니다. D – Powers

답변

1

당신은 기능 $.ajax 전달되고 있습니다

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

그 기능은 일반적인 옵션 $.ajax은 일반적으로 얻을 수 있지만,이 부대의 객체 반환 발생합니다. 그 결과 $.ajax은 (는) $.ajax([settings]) 양식 대신 $.ajax(url, [settings]) 양식을 사용하고 있다고 생각합니다. 따라서 $.ajax은 함수가 URL이고 로그에 엉망이 된 것은 문자열 화 된 함수를 URL 인코딩 한 결과라고 생각합니다.

를 드롭 -> :

$.ajax 
    url: "http://localhost:3000/historic_returns.json" 
    # as you have now... 
관련 문제