978

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

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

4

30 回答 30

1396

浏览器(和 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);
}
于 2010-10-27T12:43:51.507 回答
211

新的API 是使用 ES6 承诺window.fetch的更清洁的替代品。这里XMLHttpRequest有一个很好的解释,但归结为(来自文章):

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

浏览器支持现在在最新版本中很好(适用于 Chrome、Firefox、Edge (v14)、Safari (v10.1)、Opera、Safari iOS (v10.3)、Android 浏览器和 Chrome for Android),但 IE 会可能得不到官方支持。GitHub 有一个可用的 polyfill,建议支持仍在大量使用的旧版浏览器(尤其是 2017 年 3 月之前的 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;
}
于 2016-07-11T00:45:57.590 回答
208

在 jQuery 中

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);
于 2008-10-29T16:38:26.017 回答
173

上面有很多很好的建议,但不是很可重用,而且经常充满 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
});
于 2014-02-27T18:03:11.683 回答
101

没有回调的版本

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
于 2010-11-08T09:50:21.697 回答
75

这是直接使用 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;
        }                    
    }
}
于 2008-10-29T16:35:06.540 回答
59

复制粘贴现代版本(使用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);
于 2014-08-18T07:23:27.400 回答
47

短而干净:

const http = new XMLHttpRequest()

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

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

于 2017-10-28T18:42:52.860 回答
23

IE 将缓存 URL 以加快加载速度,但如果您在一段时间内轮询服务器以尝试获取新信息,则 IE 将缓存该 URL,并可能返回您一直拥有的相同数据集。

不管你最终如何处理你的 GET 请求 - vanilla JavaScript、Prototype、jQuery 等 - 确保你设置了一个机制来对抗缓存。为了解决这个问题,请在您要访问的 URL 的末尾附加一个唯一标记。这可以通过以下方式完成:

var sURL = '/your/url.html?' + (new Date()).getTime();

这将在 URL 的末尾附加一个唯一的时间戳,并防止发生任何缓存。

于 2008-10-29T16:40:06.357 回答
19

现代,干净,最短

fetch('https://www.randomtext.me/api/lorem')

let url = 'https://www.randomtext.me/api/lorem';

// to only send GET request without waiting for response just call 
fetch(url);

// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));

// or async/await
(async()=> 
  console.log('\nREQUEST 3', await(await fetch(url)).json()) 
)();
Open Chrome console network tab to see request

于 2020-05-12T11:20:20.840 回答
14

原型让它变得非常简单

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});
于 2008-10-29T16:35:26.570 回答
13

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

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

也许有点矫枉过正,但你绝对可以安全地使用这段代码。

用法:

//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();
于 2016-07-20T11:23:44.080 回答
10

推荐的方法是使用 JavaScript Promises 来执行此 Fetch API。XMLHttpRequest (XHR)、IFrame 对象或动态<script>标记是较旧(且较笨重)的方法。

<script type=“text/javascript”&gt; 
    // 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>

这是一个很棒的fetch 演示MDN 文档

于 2018-07-11T21:51:33.590 回答
9

我不熟悉 Mac OS Dashcode Widgets,但如果它们让您使用 JavaScript 库并支持XMLHttpRequests,我会使用jQuery并执行以下操作:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});
于 2008-10-30T04:03:53.047 回答
6

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

于 2008-10-29T19:42:10.373 回答
6

您可以通过两种方式获取 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);
      }});
    }); 
    
于 2014-09-26T13:21:08.203 回答
6

对于那些使用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.
  });
于 2015-05-06T20:36:35.380 回答
5

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

于 2008-10-29T23:01:11.080 回答
5

现在有了异步 js,我们可以使用这个方法和 fetch() 方法以更简洁的方式做出承诺。所有现代浏览器都支持异步函数。

async function funcName(url){
    const response = await fetch(url);
    var data = await response.json();
    }

于 2021-05-09T06:01:50.093 回答
5

一组功能简单易行

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


  1. 让一些基本常数

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

  1. 最简单的

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

  1. 使用 Promises 和 Async 工具的变体

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

    })
}

  1. 一个班轮功能的演示!!!

// 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())
            )
)();

  1. 最佳答案 - > By @tggagne展示了 HttpClient API 的功能。

使用 Fetch 也可以达到同样的效果。根据MDN 的Using Fetch,展示了如何将 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
  });

节点

Fetch 在节点(服务器端)上不可用

最简单的解决方案(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));
于 2021-08-04T17:39:48.147 回答
4
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/')

发布请求也可以做同样的事情。
看看这个链接JavaScript post request like a form submit

于 2016-07-03T09:34:38.563 回答
4

为了刷新 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();
    });
}
于 2018-06-27T14:01:16.887 回答
4

简单的异步请求:

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();
}
于 2018-11-18T16:56:05.233 回答
3

阿贾克斯

最好使用PrototypejQuery之类的库。

于 2008-10-29T16:33:21.910 回答
2
// 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()
于 2019-09-05T06:00:18.123 回答
2

在纯 javascript 中并返回一个 Promise:

  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();
    });
  }
于 2021-08-23T17:56:32.970 回答
1

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

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

于 2010-08-07T05:03:15.710 回答
0

你也可以用纯 JS 做到这一点:

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}

// Make the actual CORS request.
function makeCorsRequest() {
 // This is a sample server that supports CORS.
 var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}

// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};

xhr.send();
}

请参阅:了解更多详情:html5rocks 教程

于 2016-10-11T16:02:56.180 回答
0

这是 xml 文件的替代方法,可将文件作为对象加载并以非常快速的方式将属性作为对象访问。

  • 注意,为了让 javascript 能够正确解释内容,有必要将文件保存为与 HTML 页面相同的格式。如果您使用 UTF 8 将文件保存为 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
于 2019-03-15T10:34:25.603 回答
0
<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>
于 2019-09-06T06:06:39.280 回答