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

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


当前回答

我不熟悉Mac OS的Dashcode小部件,但如果他们让你使用JavaScript库和支持xmlhttprequest,我会使用jQuery,做这样的事情:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});

其他回答

一个复制粘贴的现代版本(使用fetch和箭头函数):

//Option with catch
fetch( textURL )
   .then(async r=> console.log(await r.text()))
   .catch(e=>console.error('Boo...' + e));

//No fear...
(async () =>
    console.log(
            (await (await fetch( jsonURL )).json())
            )
)();

复制粘贴的经典版本:

let request = new XMLHttpRequest();
request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            document.body.className = 'ok';
            console.log(this.responseText);
        } else if (this.response == null && this.status === 0) {
            document.body.className = 'error offline';
            console.log("The computer appears to be offline.");
        } else {
            document.body.className = 'error';
        }
    }
};
request.open("GET", url, true);
request.send(null);

jQuery:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

要做到这一点,建议使用Fetch API,使用JavaScript Promises。XMLHttpRequest (XHR)、IFrame对象或动态<script>标记是较旧(且较笨重)的方法。

<script type=“text/javascript”> 
    // Create request object 
    var request = new Request('https://example.com/api/...', 
         { method: 'POST', 
           body: {'name': 'Klaus'}, 
           headers: new Headers({ 'Content-Type': 'application/json' }) 
         });
    // Now use it! 

   fetch(request) 
   .then(resp => { 
         // handle response 
   }) 
   .catch(err => { 
         // handle errors 
    });
</script>

这里有一个很棒的获取演示和MDN文档

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)

request.onload = function () {
  // Begin accessing JSON data here
}

// Send request
request.send()

上面有很多很好的建议,但不是很可重用,而且经常充满了DOM废话和其他隐藏了简单代码的无用之处。

下面是我们创建的一个可重用且易于使用的Javascript类。目前它只有一个GET方法,但这对我们来说是可行的。添加POST不应该对任何人的技能征税。

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

使用它就像:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});