Live Update Get Request [closed]

我与影子孤独终老i 提交于 2019-12-13 09:56:12

问题


Using javascript / another client side scripting language I need to show the result of a http get request, and update every X seconds without refreshing. The api I am working with is external and works like this: You send it a request, no parameters, and it returns a number. I need to display this in a static html site and live update it every 2 seconds.

So far I have been able to live update using functions like Math.random() and setInterval but my trouble is making a GET request inside the JavaScript, to an external domain. I have a working php script that provides the result but I do not know how to integrate this into the JS


回答1:


I strongly advice to call the function again inside the success of the api call. A solution using setInterval may hammer the site even when it gives errors. Also the request can take longer than 2 second to execute

Here I use jQuery for simplicity's sake

Use setTimeout inside the success:

function getIt() { 
  $.get("url",function(data) { 
    $("#container").text(data); 
    setTimeout(getIt,2000);
  });
}
getIt();

If the URL is crossdomain, you may want to look into JSON and CORS: How to get a cross-origin resource sharing (CORS) post request working




回答2:


Just use Ajax and setInterval():

setInterval(function(){ 

//your Ajax call goes here 

}, 2000);


来源:https://stackoverflow.com/questions/38283721/live-update-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!