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

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


当前回答

为了刷新来自joann的最佳答案,这是我的代码:

let httpRequestAsync = (method, url) => {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = function () {
            if (xhr.status == 200) {
                resolve(xhr.responseText);
            }
            else {
                reject(new Error(xhr.responseText));
            }
        };
        xhr.send();
    });
}

其他回答

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

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

你可以通过两种方式获得HTTP get请求:

该方法基于xml格式。您必须为请求传递URL。 xmlhttp.open(“获得”、“URL”,真正的); xmlhttp.send (); 它是基于jQuery的。您必须指定要调用的URL和function_name。 $ (btn) .click(函数(){ 美元。Ajax ({url: "demo_test.txt", success: function_name(result) { $ (" # innerdiv ") . html(结果); }}); });

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请求像一个表单提交

原型让它变得非常简单

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});

短的、干净的:

const http = new XMLHttpRequest() http。打开(“得到”,“https://api.lyrics.ovh/v1/toto/africa”) http.send () http。onload = () => console.log(http.response)