2008-10-29 174 views
562

我需要在JavaScript中执行HTTP GET请求。什么是最好的方式来做到这一点?JavaScript中的HTTP GET请求?

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

+8

注意,这是受同源策略。 http://en.wikipedia.org/wiki/Same_origin_policy – ripper234 2011-10-06 21:10:02

回答

926

您可以通过JavaScript使用由主机环境提供的功能:

function httpGet(theUrl) 
{ 
    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open("GET", theUrl, false); // false for synchronous request 
    xmlHttp.send(null); 
    return xmlHttp.responseText; 
} 

然而,同步请求都望而却步,所以你可能要改为使用:

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

Note: Starting with Gecko 30.0 (Firefox 30.0/Thunderbird 30.0/SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

68

这里是直接使用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; 
     }      
    } 
} 
+27

由于这个答案是谷歌搜索“HTTP请求的JavaScript”的最高结果之一,值得一提的是,对这样的响应数据运行eval被认为是不好的做法 – Kloar 2014-05-19 09:47:10

+7

@Kloar好点,但是给出它不好的原因会更好,我认为这是安全性。 解释为什么做法不好是让人们改变习惯的最佳方式。 – Balmipour 2015-09-16 11:16:18

11

Prototype使得它死了简单

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

问题是Mac OS X没有预装Prototype。由于小部件需要在任何计算机上运行,​​包括每个小部件中的Prototype(或jQuery)并不是最佳解决方案。 – kiamlaluno 2010-08-07 05:05:52

+0

@kiamlaluno使用Cloudflare的Prototype cdn – 2017-02-14 10:34:19

166

In jQuery

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

请注意,当您尝试访问不同于域名的域名中的网址时,IE 10无法正常工作 – BornToCode 2013-09-30 09:35:35

+5

@BornToCode您应该进一步调查并可能在jQuery问题跟踪器中打开一个错误在那种情况下 – ashes999 2013-10-08 16:58:42

+68

我知道有些人想写纯Javascript。我明白了。在他们的项目中做这件事我没有问题。我的“在jQuery中:”应该被解释为“我知道你问过如何在Javascript中做到这一点,但让我告诉你如何用jQuery来做到这一点,你可能会看到什么样的语法简洁和清晰度,你可以通过使用这个图书馆,这将给你提供许多其他的优势和工具,以及享受“。 – Pistos 2014-06-26 19:47:09

14

IE将缓存的URL,以使装载速度更快,但如果你是,比如说,轮询服务器每隔一段时间试图获取新信息,IE都会缓存该URL,并且可能会返回您始终拥有的相同数据集。不管你如何最终做GET请求 - 香草JavaScript,Prototype,jQuery等 - 确保你提供了一种机制来对抗缓存。为了解决这个问题,请在您将要访问的网址的末尾追加一个唯一标记。这可以通过以下方式完成:

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

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

3

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

2

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

6

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

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

Dashboard小部件的代码,并且您不希望在创建的每个小部件中包含JavaScript库,那么您可以使用Safari本机支持的对象XMLHttpRequest。

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

78

一版本无回调

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

上面提供了很多很好的建议,但不是很可重用,而且经常充满了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 
}); 
25

拷贝粘贴准备版本

var request = new XMLHttpRequest(); 
request.onreadystatechange = function() { 
    if (request.readyState === 4) { 
     if (request.status === 200) { 
      document.body.className = 'ok'; 
      console.log(request.responseText); 
     } else if (!isValid(this.response) && 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); 
2

您可以通过两种方式得到一个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); 
        }}); 
    }); 
    
3

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

它也可能证明是非常有益的尝试REQUESTIFY-,简化了节点的HTTP请求制作一个图书馆。

https://github.com/ranm8/requestify

var requestify = require('requestify'); 

获取的请求:

requestify.get('http://example.com').then(function(response) { 
    // Get the response body 
    response.getBody(); 
}); 

并以JSON:

requestify.post('http://example.com', { 
     hello: 'world' 
    }) 
    .then(function(response) { 
     // Get the response body (JSON parsed or jQuery object for XMLs) 
     response.getBody(); 

     // Get the raw response body 
     response.body; 
    }); 
2
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请求进行为好。
看一看这个链接JavaScript post request like a form submit

42

window.fetch API是XMLHttpRequest清洁更换,使得使用ES6的承诺。有一个很好的解释here,但它归结为(文章):

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

Browser support是现在最新版本好(在Chrome,火狐,边缘(V14)的作品,Safari浏览器(10.1) ,Opera,Safari iOS(v10.3),Android浏览器和Android版Chrome),但IE可能无法获得官方支持。 GitHub has a polyfill推荐用于支持仍在使用中的较旧浏览器(尤其是2017年3月前的Safari版本以及同期的移动浏览器)。

我猜这是否比jQuery或XMLHttpRequest更方便取决于项目的性质。

这里有一个链接到规范https://fetch.spec.whatwg.org/

编辑:异步的await,这成为简单(基于this Gist)/

使用ES7:

async function fetchAsync (url) { 
    let response = await fetch(url); 
    let data = await response.json(); 
    return data; 
} 
1

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

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(ee) 
      { 
       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 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(); 
} 

参见:

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

短而纯粹:

const http = new XMLHttpRequest() 
 

 
http.open("GET", "https://api.lyrics.ovh/v1/shakira/waka-waka") 
 
http.send() 
 

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