2016-12-24 53 views
1

我有一個用Ruby編寫的API代碼,它在循環中的請求中調用API,因爲我們最多可以得到50個結果。但我想在jQuery中創建這個API請求。我不知道我將如何做到這一點。如何在jQuery中獲取和發佈API請求?

這裏是我的Ruby代碼:

totalsequence = [] 
    start = 0 
    begin 
     response = HTTParty.get("https://api.ontraport.com/1/objects?objectID=5&start=" + start.to_s, 
     { 
      :headers => { 'Api-Appid' => '', 'Api-Key' => ''} 
     }) 
     totalsequence = totalsequence + response['data'] 
     start += 50 
    end until (response['data']).size == 0 
    render json: JSON.pretty_generate(totalsequence) 

所以我想這個代碼轉換爲jQuery的。

+0

我不是你問清楚了嗎? – MZaragoza

+1

如果只是將上面的代碼轉換爲jQuery,快速谷歌搜索會導致大量代碼示例。 – Sid

+0

[jQuery Ajax簡單調用]的可能重複(http://stackoverflow.com/questions/19015897/jquery-ajax-simple-call) –

回答

3

在jQuery中您可以使用jQuery.ajax這樣的:

$.ajax({ 
    url: "https://api.ontraport.com/1/objects?objectID=5&start=" + start.to_s, 
    type: 'GET', 
    headers: { 
     'Api-Appid': '2_7861_X3YeBz0j1', 
     'Api-Key': 'NXhYJvz2AsywN80' 
    }, 
    data { 
     'key1': 'value1', 
     'key2': 'value2', 
     ... 
    }, 
    dataType: 'json', 
    success: function(data) { 
     // handle success here via accessing data variable 
     // returned from the server as response 
    }, 
    error: function(error) { 
     // handle error here via accessing error variable 
    }, 
}); 

data屬性指定發送到服務器,這應該是在鍵值對的數據。

查看更多about jQuery Ajax Properties

+0

我得到這個錯誤'跨源請求被阻止:同源策略不允許在https://api.ontraport.com/1/objects?objectID=5&start=50中讀取遠程資源(原因:CORS header'Access-Control-Allow-Origin'missing)。' –

+2

請確保您在請求的服務器上啓用CORS ...請參閱 - http://enable-cors.org/server.html –

+0

@ElsieHamilton - 如果您發現此答案正確無誤且樂於助人,請接受&upvote此答案,因爲它可以激勵我回答此類問題並幫助他人快速找到正確答案! –

2

你只是試試這個。

Ajax post

$.ajax({ 
    type: "POST", 
    url: url, 
    data: data, 
    success: success, 
    dataType: dataType 
}); 

Ajax get

$.ajax({ 
    url: url, 
    data: data, 
    success: success, 
    dataType: dataType 
}); 
+0

我不想它去ruby控制器 –

+0

如果不是Rails控制器,那麼呢?此外,不應該在Ajax請求中的URL說'/創建' – Sid

+0

好的等待@ElsieHamilton –