![](/img/trans.png)
[英]How to send AJAX post request and receive back JSON data in Vanilla JS?
[英]how to send a post request and receive json back in rails
我已經仔細研究了很多問題-但是,我仍然感到困惑。
我正在制作一個與Healthgraph API(此處為http://developer.runkeeper.com/healthgraph/registration-authorization )連接的Rails應用程序。
我應該通過Rails發出POST請求-基於我接收的參數,然后接收JSON。 我已經嘗試過outh2,runkeeper和其他gems,但由於某種依賴性它們無法工作。 但是,我不知道如何通過Rails進行POST並收到響應。
我確實在控制器中獲取了代碼-但是,我仍然不知道如何獲取訪問令牌。
防御測試
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(\''+@code+'\',\''+@cc_id+'\',\''+@cc_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"}}
我要在控制器文件頂部使用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,則response_to塊也將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.