2012-01-16 28 views
1

我已經瀏覽了相當多的問題 - 但是,我仍然感到困惑。如何發送郵寄請求並接收json回來的鐵軌

我正在製作一個與Healthgraph API連接的Rails應用程序(此處爲http://developer.runkeeper.com/healthgraph/registration-authorization)。

我應該通過Rails發出一個POST請求 - 基於一個參數我收到然後收到JSON。我已經嘗試了outh2,runkeeper和其他寶石,他們不工作,因爲有一定的依賴性。但是,我迷失於如何通過Rails進行POST並收到響應。

我確實把代碼拿回了我的控制器 - 但是,我仍然不知道如何獲得訪問令牌。

高清rktest

respond_to 

if params[:code] 
    require 'oauth2' 

    @code=params[:code] 

    @cc_id=client_id 
    @client_s=client_secret 

else 

    @code="None" 

end 

我試圖通過Javascript也做到這一點 - 但我寧願不要 - 因爲它離開我的裸露端密鑰。另外,我也沒有收到數據。

<script type="text/javascript" src="javascripts/jquery-1.7.1.min.js"></script> 

<script type="text/javascript"> 

function get_access_token(code,ccid,cc_s){ 

$.ajaxSetup({ 
'beforeSend': function(xhr){ 
xhr.setRequestHeader("Accept", "text/javascript") 
} 
}); 

var sent = { 'grant_type': 'authorization_code', 
'code': code, 
'client_id': ccid, 
'client_secret': cc_s, 
'redirect_uri': 'http://myurl.com/rktest' 
}; 

document.write("<p>" + sent + "</p>"); 

$.ajax({ 
url: 'https://runkeeper.com/apps/token', 
data: sent, 
type: 'POST', 
dataType: 'json', 
success: function(data, status, xhr){ 
if (status === 'error' || !xhr.responseText){ 
handleError(); 
}else{ 

document.write("<p>" + data + "</p>"); 
document.write("<p>" + status + "</p>"); 
document.write("<p>" + xhr + "</p>"); 

} 
} 
}); 

} 

<%= 'get_access_token(\''[email protected]+'\',\''[email protected]_id+'\',\''[email protected]_s+'\');' %>     

而且,這裏是目前我的路線文件:

match '/rktest', :to => 'main#rktest', :via => [:get, :post] 

即使這是行不通的。

RestClient.post 'https://runkeeper.com/apps/token', {:params => { 
    :grant_type => 'authorization_code', 
    :code => @code, 
    :client_id => '8e9b36478b764ac38ef1bdabc6d14d60', 
    :client_secret => something, 
:redirect_uri => "http%3A%2F%2Fopenhealthdesigns.com%2Frktest"}} 

回答

0

我使用respond_to :json在,我希望返回JSON的方法與respond_with @notes控制器文件的頂部,並且效果很好。

該應用程序使用Ajax來返回搜索功能的數據,但我不認爲數據如何被調用應該有所作爲。

豆蔻上下文更多的代碼:

class NotesController < ApplicationController 
    require 'coderay' 
    respond_to :json                                                   


def search 
    @notes = Note.fulltext_search(params[:title]) 
    @notes.each do |n| 
    n.content = CodeRay.scan(n.content, :ruby).div(:css => :class) 
    end 
    respond_with @notes 
end 

API文件 - 這取決於如何該方法將被調用。如果使用.json,respond_to塊也可以。

respond_with

respond_to

+0

IM困惑,你是什麼意思?你在哪裏發佈到外部服務器? – econclicks 2012-01-16 21:12:09

+0

這實際上是一個get請求,但請求的類型應該不重要。我向您展示了我如何在Rails 3.1應用程序中返回json。如果您將respond_to:json行放入您的文件並使用respond_with ,它將返回json。 – 2012-01-17 04:45:25