JavaScript'te HTTP GET isteği?

JavaScript'te bir HTTP GET isteği yapmam gerekiyor. Bunu yapmanın en iyi yolu nedir?

Bunu bir Mac OS X dashcode widget'ında yapmam gerekiyor.

İşte bunu doğrudan JavaScript ile yapmak için kod. Ancak, daha önce de belirtildiği gibi, bir JavaScript kütüphanesi kullanmanız çok daha iyi olacaktır. Benim favorim jQuery.

Aşağıdaki durumda, bir JavaScript JSON nesnesi döndürmek için bir ASPX sayfası (yoksul bir adamın REST hizmeti olarak hizmet veren) çağrılmaktadır.

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

Prototype bunu son derece basit hale getirir

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

Ajax

Prototype]2 veya jQuery gibi bir kütüphane kullanmanız daha iyi olacaktır.

Yorumlar (0)