views:

24878

answers:

13

I need to do an HTTP GET request in JS, what's the best way to do that?

Thanks

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

+2  A: 

AJAX.

You'd be best off using a library such as prototype or jquery

Greg
+1  A: 

Here's the example in jQuery

Vinko Vrsalovic
+3  A: 

This is the basis of AJAX - Google for that and XMLHttpRequest and you'll find plenty of code samples.

Alnitak
+12  A: 

Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.

In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.

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;
        }                    
    }
}
rp
+4  A: 

Prototype makes it dead simple

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});
Mark Biek
The problem is that Mac OS X doesn't come with Prototype pre-installed. As the widget needs to run in any computer, including Prototype (or jQuery) in each widget is not the best solution.
kiamlaluno
+12  A: 

In jQuery:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);
Pistos
This is wrong. jQuery's get method does not return the result, though it allows you to specify a callback.
Daniel Beardsley
I've edited and changed the example.
nickf
My apologies! Thanks for editing.
Pistos
+1  A: 

IE will cache URLs in order to make laoding faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.

Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:

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

This will append a unique timestamp to the end of the URL and will prevent any caching from happening.

Tom
+1  A: 

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

Andrew Hedges
+1  A: 

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.

Nikola Stjelja
+1  A: 

I'm not familiar with Mac OS Dashcode Widgets, but if they let you use javascript libraries and support XMLHTTPRequests, I'd use jQuery and do something like this:

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

what if I want to take from the site http://host/somepage.php

like

var page_content; $. Get ("http://host/somepage.php", function (data) ( page_content = data; ));

syamsy
A: 

If you want to use the code for a Dashboard widget, and you don't want to include a JavaScript library in every widget you created, then you can use the object XMLHttpRequest that Safari natively supports.

As reported by Andrew Hedges, a widget doesn't have access to a network, by default; you need to change that setting in the info.plist associated with the widget.

kiamlaluno
A: 

What the heel about all those fancy libraries, JavaScript has it built-in:

function httpGet(theUrl) { var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;

}

Joan