简体   繁体   中英

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. Now, 'localhost:4567/get/233310/loc' returns a JSON object

[{"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? (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.

Can anyone help me with this??

Thank you.

Another useful library is called Prototype. Read about it here:

http://www.prototypejs.org/

The code to make a request like this in Prototype is really easy. Just include the prototype.js library on your page:

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

Then run this code:

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()); } });

When this completes, you should see a pop up alert with the contents of your JSON object displayed.

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.

Hope this is useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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