JavaScript中的HTTP GET请求?

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

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


#1楼

上面有很多很棒的建议,但不是很可重用,并且经常被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
});

#2楼

阿贾克斯

最好使用PrototypejQuery之类的库。


#3楼

这是直接用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;
        }                    
    }
}

#4楼

原型使其变得简单

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

#5楼

在jQuery中

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

#6楼

IE会缓存URL以加快加载速度,但是,例如,如果您要定期轮询服务器以获取新信息,则IE会缓存该URL并可能返回您一直拥有的相同数据集。

不管最终如何执行GET请求-原始JavaScript,Prototype,jQuery等-确保您已建立适当的机制来对抗缓存。 为了解决这个问题,请将唯一的令牌附加到您将要访问的URL的末尾。 这可以通过以下方式完成:

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

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


#7楼

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


#8楼

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


#9楼

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

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

#10楼

复制粘贴的现代版本(使用访存箭头功能

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

#11楼

您可以通过两种方式获取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); }}); }); 

#12楼

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

#13楼

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

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


#14楼

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发布请求,例如表单提交


#15楼

新的window.fetch API是使用ES6承诺的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月之前的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;
}

#16楼

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

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

#17楼

您也可以使用纯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教程


#18楼

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

#19楼

没有回调的版本

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

#20楼

简短而干净:

 const http = new XMLHttpRequest() http.open("GET", "https://api.lyrics.ovh/v1/toto/africa") http.send() http.onload = () => console.log(http.responseText) 


#21楼

为了刷新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();
    });
}

#22楼

为此,建议使用JavaScript Promises来获取API。 XMLHttpRequest(XHR),IFrame对象或动态标签是较旧的(且笨拙的)方法。

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

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


#23楼

简单的异步请求:

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

#24楼

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

这只是向小组献礼的小礼物。 谢谢你的喜欢:)

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

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

#25楼

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

#26楼

<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>
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值