简体   繁体   English

本地托管API中带有JSON对象的javascript的http请求

[英]http request with javascript for JSON object in a locally hosted API

I have a API running on my machine locally written in sinatra and jruby which interacts with a sql server. 我在本地用sinatra和jruby编写的与SQL Server交互的机器上运行着一个API。 Now, 'localhost:4567/get/233310/loc' returns a JSON object 现在,“ localhost:4567 / get / 233310 / loc”返回一个JSON对象

[{"uid":233307,"lat":41.4191113333333,"long":-72.8941905}]

What I want to do, for now is get this JSON object and assign each of the object to a variable in my javascript..which I think would best done with a http request? 我现在想做的是获取此JSON对象并将每个对象分配给javascript中的变量。我认为最好用http请求完成此操作? (if there's a better way..please do let me know). (如果有更好的方法,请告诉我)。

Eventually, I need this to make the request every 30 secs but I will deal with that later. 最终,我需要这样做才能每30秒发出一次请求,但稍后我会处理。

Can anyone help me with this?? 谁能帮我这个??

Thank you. 谢谢。

Another useful library is called Prototype. 另一个有用的库称为原型。 Read about it here: 在这里阅读:

http://www.prototypejs.org/ http://www.prototypejs.org/

The code to make a request like this in Prototype is really easy. 在Prototype中发出这样的请求的代码非常简单。 Just include the prototype.js library on your page: 只需在页面上包含prototype.js库即可:

<script src="prototype.js"></script>

Then run this code: 然后运行以下代码:

var url = 'http://localhost:4567/get/233310/loc'; var url ='http:// localhost:4567 / get / 233310 / loc'; new Ajax.Request(url, { method: 'get', onSuccess: function(transport) { var json = transport.responseJSON; window.alert(json.inspect()); } }); 新的Ajax.Request(URL,{方法:'get',onSuccess:function(transport){var json = transport.responseJSON; window.alert(json.inspect());}});

When this completes, you should see a pop up alert with the contents of your JSON object displayed. 完成后,您应该会看到一个弹出警报,其中显示了JSON对象的内容。

Your server side script should serve up the JSON with the HTTP header "Content-Type" set to "application/json" so that the client side script code understands that it should try to parse it as JSON. 您的服务器端脚本应在HTTP标头“ Content-Type”设置为“ application / json”的情况下提供JSON,以便客户端脚本代码理解应尝试将其解析为JSON。

Hope this is useful. 希望这是有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM