首页 文章

JavaScript中的HTTP GET请求?

提问于
浏览
649

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

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

23 回答

  • 4

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

    为此,使用JavaScript Promises建议使用Fetch 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>
    

    这是一个伟大的fetch demoMDN docs

  • 5

    如果要将代码用于Dashboard窗口小部件,并且不希望在您创建的每个窗口小部件中包含JavaScript库,则可以使用Safari本机支持的对象XMLHttpRequest .

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

  • 4

    没有回调的版本

    var i = document.createElement("img");
    i.src = "/your/GET/url?params=here";
    
  • 0
    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

  • 69

    Ajax

    你最好使用像PrototypejQuery这样的库 .

  • 5

    您可以通过两种方式获取HTTP GET请求:

    • 这种方法基于xml格式 . 您必须传递请求的URL .
    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
    • 这个基于jQuery . 您必须指定要调用的URL和function_name .
    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    });
    
  • 12

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

    无论你最终如何做你的GET请求 - vanilla JavaScript,Prototype,jQuery等 - 确保你 Build 了一个机制来对抗缓存 . 为了解决这个问题,请在您要访问的URL的末尾附加一个唯一的令牌 . 这可以通过以下方式完成:

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

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

  • 4

    Short and pure:

    const http = new XMLHttpRequest()
    
    http.open("GET", "https://api.lyrics.ovh/v1/shakira/waka-waka")
    http.send()
    
    http.onload = () => console.log(http.responseText)
    
  • 15

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

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

    新的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,Firefox,Edge(v14),Safari(v10.1),Opera,Safari iOS(v10.3),Android浏览器和Android版Chrome),但IE很可能没有获得官方支持 . GitHub has a polyfill可用,建议支持仍在使用中的旧版浏览器(2017年3月之前的Safari版本和同期的移动浏览器) .

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

    这是规范的链接https://fetch.spec.whatwg.org/

    Edit

    使用ES7 async / await,这变得简单(基于this Gist):

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

    以下是使用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;
            }                    
        }
    }
    
  • 3

    复制粘贴就绪版本

    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);
    
  • 8

    您可以通过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);
    }
    

    注意:从Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用 .

  • 1

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

  • 0

    Prototype让它变得简单

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

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

  • 17

    要刷新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();
        });
    }
    
  • 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
    });
    
  • 176

    在您的小部件中's Info.plist file, don' t忘记将 AllowNetworkAccess 键设置为true .

  • 128

    In jQuery

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

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

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

    也许有点矫枉过正,但你肯定对这段代码安全 .

    Usage:

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

    简单的异步请求:

    function get(url, callback) {
      var xhttp = new XMLHttpRequest();
    
      xhttp.open("GET", "https://example.com/path");
    
      xhttp.onreadystatechange = function() {
        callback(xhttp.responseText);
      }
    
      xhttp.send();
    }
    

相关问题