小编典典

JavaScript中的HTTP GET请求?

javascript

我需要在JavaScript中执行HTTPGET请求。最好的方法是什么?

我需要在Mac OS X破折号小部件中执行此操作。


阅读 1756

收藏
2020-04-22

共1个答案

小编典典

浏览器(和Dashcode)提供XMLHttpRequest对象,该对象可用于从JavaScript发出HTTP请求:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

但是,不鼓励同步请求,并且将按照以下方式生成警告:

注意:从Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey
2.27)开始,由于对用户体验的负面影响, 主线程上的同步请求已被弃用

您应该发出异步请求并在事件处理程序中处理响应。

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);
}
2020-04-22