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

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


当前回答

对于那些使用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.
  });

其他回答

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

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

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

您应该在事件处理程序中发出异步请求并处理响应。

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和返回一个承诺:

  httpRequest = (url, method = 'GET') => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.onload = () => {
        if (xhr.status === 200) { resolve(xhr.responseText); }
        else { reject(new Error(xhr.responseText)); }
      };
      xhr.send();
    });
  }

这里有一个xml文件的替代方案,以非常快的方式将文件作为对象加载和访问属性作为对象。

注意,为了使javascript能够正确地解释内容,有必要将文件保存为与HTML页面相同的格式。如果你使用UTF8保存你的文件在UTF8等。

XML就像树一样?而不是写作

     <property> value <property> 

写一个简单的文件,像这样:

      Property1: value
      Property2: value
      etc.

保存文件.. 现在调用函数....

    var objectfile = {};

function getfilecontent(url){
    var cli = new XMLHttpRequest();

    cli.onload = function(){
         if((this.status == 200 || this.status == 0) && this.responseText != null) {
        var r = this.responseText;
        var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
        if(b.length){
        if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
        r=j.split(b);
        r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
        r = r.map(f => f.trim());
        }
        if(r.length > 0){
            for(var i=0; i<r.length; i++){
                var m = r[i].split(':');
                if(m.length>1){
                        var mname = m[0];
                        var n = m.shift();
                        var ivalue = m.join(':');
                        objectfile[mname]=ivalue;
                }
            }
        }
        }
    }
cli.open("GET", url);
cli.send();
}

现在你可以有效地获得你的价值。

getfilecontent('mesite.com/mefile.txt');

window.onload = function(){

if(objectfile !== null){
alert (objectfile.property1.value);
}
}

这只是给大家的一份小礼物。谢谢你的喜欢:)

如果您想在本地测试该功能,请使用以下命令重新启动浏览器(除safari外所有浏览器都支持):

yournavigator.exe '' --allow-file-access-from-files

集功能,食谱容易和简单

我准备了一组函数,它们在某种程度上是相似的,但如果你知道如何利用它,就会展示新的功能以及Javascript已经达到的简单性。


让一些基本常数


let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
    data = dt;
}

最简单的


// MOST SIMPLE ONE 
function makeRequest1() {       
    fetch(URLAPI)
        .then(response => response.json()).then( json => setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 1 --> ", data);
            data = null;
    });
}

使用承诺和异步工具的变化


// ASYNC FUNCTIONS 
function makeRequest2() { 
    fetch(URLAPI)
        .then(async response => await response.json()).then(async json => await setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 2 --> ", data);
            data = null;            
        });
}

function makeRequest3() {    
    fetch(URLAPI)
        .then(async response => await response.json()).then(json => setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 3 --> ", data);
            data = null;
        });
}

// Better Promise usages
function makeRequest4() {
    const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {
        console.log("Data received 4 --> ", data);

    })
}

一个线性函数的演示!!


// ONE LINER STRIKE ASYNC WRAPPER FUNCTION 
async function makeRequest5() {
    console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );
}

值得一提的是——> @Daniel De León可能是最干净的函数*

(async () =>
    console.log(
            (await (await fetch( URLAPI )).json())
            )
)();

上面的答案-> By @tggagne显示了HttpClient API的功能。

使用Fetch也可以实现同样的效果。根据此使用MDN获取展示了如何将INIT作为第二个参数传递,基本上打开了使用经典方法(get, post…)轻松配置API的可能性。


// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

Node

在节点(服务器端)上无法获取

最简单的解决方案(2021年底)是使用Axios。

$ npm install axios

然后运行:

const axios = require('axios');
const request = async (url) => await (await axios.get( url ));
let response = request(URL).then(resp => console.log(resp.data));