JavaScript中的HTTP GET请求?

JavaScript

番长LA

2020-03-10

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

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

第514篇《JavaScript中的HTTP GET请求?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

15个回答
凯Harry 2020.03.10
<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>
老丝Gil樱 2020.03.10

阿贾克斯

最好使用PrototypejQuery之类的库

Mandy逆天 2020.03.10

To refresh best answer from joann with promise this is my code:

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();
    });
}
飞云卡卡西神乐 2020.03.10

如果要为Dashboard小部件使用代码,并且不想在创建的每个小部件中都包含JavaScript库,则可以使用Safari原生支持的XMLHttpRequest对象。

根据Andrew Hedges的报告,默认情况下,小部件无法访问网络。您需要在与小部件关联的info.plist中更改该设置。

小宇宙猴子 2020.03.10

简单的异步请求:

function get(url, callback) {
  var getRequest = new XMLHttpRequest();

  getRequest.open("get", url, true);

  getRequest.addEventListener("readystatechange", function() {
    if (getRequest.readyState === 4 && getRequest.status === 200) {
      callback(getRequest.responseText);
    }
  });

  getRequest.send();
}
凯JinJin 2020.03.10

您可以通过两种方式获取HTTP GET请求:

  1. 这种方法基于xml格式。您必须传递请求的URL。

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. 这是基于jQuery的。您必须指定要调用的URL和function_name。

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
宝儿Davaid 2020.03.10

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

逆天理查德 2020.03.10

我不熟悉Mac OS的Dashcode窗口小部件,但是如果它们允许您使用JavaScript库并支持XMLHttpRequests,那么我将使用jQuery并执行以下操作:

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

一种支持较旧浏览器的解决方案:

function httpRequest() {
    var ajax = null,
        response = null,
        self = this;

    this.method = null;
    this.url = null;
    this.async = true;
    this.data = null;

    this.send = function() {
        ajax.open(this.method, this.url, this.asnyc);
        ajax.send(this.data);
    };

    if(window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        catch(e) {
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(error) {
                self.fail("not supported");
            }
        }
    }

    if(ajax == null) {
        return false;
    }

    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                self.success(this.responseText);
            }
            else {
                self.fail(this.status + " - " + this.statusText);
            }
        }
    };
}

也许有些矫kill过正,但是使用此代码绝对可以放心。

用法:

//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";

//create callback for success containing the response
request.success = function(response) {
    console.log(response);
};

//and a fail callback containing the error
request.fail = function(error) {
    console.log(error);
};

//and finally send it away
request.send();
十三村村蛋蛋 2020.03.10

在小部件的Info.plist文件中,不要忘记将AllowNetworkAccess密钥设置为true。

Stafan逆天 2020.03.10

这是直接使用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;
        }                    
    }
}
宝儿小哥小卤蛋 2020.03.10

简短而干净:

const http = new XMLHttpRequest()

http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()

http.onload = () => console.log(http.responseText)

凯老丝 2020.03.10

没有回调的版本

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
null 2020.03.10

新的window.fetchAPI是XMLHttpRequest使用ES6承诺的更干净的替代品有一个很好的解释在这里,但它归结为(文章):

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function() {
  console.log("Booo");
});

浏览器支持目前最新的版本好(在Chrome,火狐,边缘(V14)的作品,Safari浏览器(10.1),歌剧,Safari浏览器的iOS(10.3),Android浏览器和Android版Chrome),然而IE会可能无法获得官方支持。GitHub上有可用的polyfill,建议它支持仍在大量使用的旧版浏览器(2017年3月之前的esp版本的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;
}
JinJinPro 2020.03.10

浏览器(和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)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用

You should make an asynchronous request and handle the response inside an event handler.

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);
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android