JavaScript中的HTTP GET请求?

JavaScript中的HTTP GET请求?

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

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


千巷猫影
浏览 5255回答 4
4回答

慕姐8265434

浏览器(和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);}

料青山看我应如是

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

喵喔喔

上面有很多很棒的建议,但不是很容易重复使用,而且经常充斥着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});

MMTTMM

没有回调的版本var i = document.createElement("img"); i.src = "/your/GET/url?params=here";
打开App,查看更多内容
随时随地看视频慕课网APP