HTTP GET request in JavaScript?

2018-12-31 00:40发布

I need to do an HTTP GET request in JavaScript. What's the best way to do that?

I need to do this in a Mac OS X dashcode widget.

23条回答
深知你不懂我心
2楼-- · 2018-12-31 00:42

The best way is to use AJAX ( you can find a simple tutorial on this page Tizag). The reason is that any other technique you may use requires more code, it is not guaranteed to work cross browser without rework and requires you use more client memory by opening hidden pages inside frames passing urls parsing their data and closing them. AJAX is the way to go in this situation. That my two years of javascript heavy development speaking.

查看更多
大哥的爱人
3楼-- · 2018-12-31 00:46

To do this Fetch API is the recommended approach, using JavaScript Promises. XMLHttpRequest (XHR), IFrame object or dynamic tags are older (and clunkier) approaches.

<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>

Here is a great fetch demo and MDN docs

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 00:47

Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.

Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.

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

Using it is as easy as:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});
查看更多
情到深处是孤独
5楼-- · 2018-12-31 00:50

To refresh best answer from joann with promise this is my code:

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();
    });
}
查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 00:51

You can get an HTTP GET request in two ways:

  1. This approach based on xml format. You have to pass the URL for the request.

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. This one is based on jQuery. You have to specify the URL and function_name you want to call.

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
查看更多
倾城一夜雪
7楼-- · 2018-12-31 00:52

In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.

查看更多
登录 后发表回答