实时更新获取请求 [英] Live Update Get Request

查看:120
本文介绍了实时更新获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript /另一种客户端脚本语言,我需要显示http get请求的结果,并且每隔X秒更新一次而不刷新。我正在使用的api是外部的,它的工作原理是这样的:
您向它发送一个请求,没有参数,它返回一个数字。我需要在一个静态html网站上显示它,并且每2秒更新一次。



到目前为止,我已经可以使用 Math.random()和setInterval,但我的麻烦是在JavaScript内部向外部域发出GET请求。我有一个工作的PHP脚本,提供了结果,但我不知道如何将它集成到JS中。

我强烈建议在api调用成功的时候再次调用函数。即使出现错误,使用setInterval的解决方案也可能会对网站产生影响。此外,请求可能需要超过2秒的时间来执行



在这里我使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆