JavaScript中的HTTP GET请求? [英] HTTP GET request in JavaScript?
问题描述
我需要在JavaScript中执行 HTTP GET 请求。什么是最好的方式做到这一点?
我需要在Mac OS X dashcode窗口小部件中执行此操作。
function httpGet( theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(GET,theUrl,false); //同步请求为false
xmlHttp.send(null);
return xmlHttp.responseText;
}
但是,不建议同步请求,所以您可能想使用它:
函数httpGetAsync(theUrl,callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4&& xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open(GET,theUrl,true); //对于异步
是真的xmlHttp.send(null);
}
注意:从Gecko 30.0开始(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27),由于对用户体验的负面影响,主线程上的同步请求已被弃用。
I need to do an HTTP GET request in JavaScript. What's the best way to do that?
I need to do this in a Mac OS X dashcode widget.
You can use functions provided by the hosting environment through javascript:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
However, synchronous requests are discouraged, so you might want to use this instead:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
这篇关于JavaScript中的HTTP GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!