我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?

我需要在Mac OS X的dashcode小部件中做到这一点。


当前回答

下面是直接用JavaScript实现的代码。但是,如前所述,使用JavaScript库会更好。我最喜欢jQuery。

在下面的例子中,调用一个ASPX页面(作为穷人的REST服务)来返回一个JavaScript JSON对象。

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}

其他回答

在你的小部件的信息。plist文件,不要忘记设置你的AllowNetworkAccess键为true。

Ajax

你最好使用Prototype或jQuery这样的库。

窗口。fetch是使用ES6承诺的XMLHttpRequest的现代替代品。这里有一个很好的解释,但它可以归结为(来自文章):

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(err) {
  console.log('Fetch Error :-S', err);
});

自2017年以来,浏览器支持一直很好。IE可能不会得到官方的支持。GitHub有一个可用的polyfill,增加了对一些传统浏览器的支持(特别是2017年3月之前的Safari版本和同期的移动浏览器)。

我想这是否比jQuery或XMLHttpRequest更方便取决于项目的性质。

这里是规范https://fetch.spec.whatwg.org/的链接

编辑:

使用ES7 async/await,这变得很简单(基于这个Gist):

async function fetchAsync (url) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}

最好的方法是使用AJAX(您可以在Tizag页面上找到一个简单的教程)。原因是你可能使用的任何其他技术都需要更多的代码,它不能保证在不返工的情况下跨浏览器工作,并且需要你通过在帧内打开隐藏页面传递url解析其数据并关闭它们来使用更多的客户端内存。 AJAX是解决这种情况的方法。这就是我两年的javascript重度开发讲的。

<button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>

 <script>
        function loadXMLDoc() {
            var xmlhttp = new XMLHttpRequest();
            var url = "<Enter URL>";``
            xmlhttp.onload = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
                    document.getElementById("demo").innerHTML = this.responseText;
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    </script>