实时更新获取请求 [英] Live Update Get Request
问题描述
您向它发送一个请求,没有参数,它返回一个数字。我需要在一个静态html网站上显示它,并且每2秒更新一次。
到目前为止,我已经可以使用 Math.random()
和setInterval,但我的麻烦是在JavaScript内部向外部域发出GET请求。我有一个工作的PHP脚本,提供了结果,但我不知道如何将它集成到JS中。
在这里我使用jQuery为了简单起见
使用setTimeout在成功内部:
pre $函数getIt(){
$ .get(url,function(data){
$(#container).text(data);
setTimeout(getIt,2000);
});
}
getIt();
如果URL是跨域,您可能需要查看JSON和CORS:
< a href =https://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working>如何获得跨源资源共享(CORS)请求工作
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
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
这篇关于实时更新获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!