2016-12-24 108 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 –

相关问题