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

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


当前回答

jQuery:

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

其他回答

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

对于那些使用AngularJs的人来说,它是$http.get:

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

现代、干净、简洁

fetch('https://baconipsum.com/api/?type=1')

让url = 'https://baconipsum.com/api/?type=all-meat&paras=1&start-with-lorem=2'; //只发送GET请求而不等待响应 fetch (url); //使用then来等待结果 获取(url)。然后(r = > r.json()。then(j=> console.log('\nREQUEST 2',j))); //或async/await (异步()= > console.log('\nREQUEST 3', await(await fetch(url)).json()) ) (); 打开Chrome控制台网络选项卡查看请求

function get(path) {
    var form = document.createElement("form");
    form.setAttribute("method", "get");
    form.setAttribute("action", path);
    document.body.appendChild(form);
    form.submit();
}


get('/my/url/')

同样的事情也可以为post request做。 看看这个链接JavaScript post请求像一个表单提交

一个复制粘贴的现代版本(使用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);