IT兄弟连 JavaWeb教程 使用AJAX发送GET请求并获取响应

GET请求用于获取数据,有时候咱们须要获取的数据须要经过"查询参数"进行定位,在这种状况下,咱们会将查询参数追加到URL的末尾,令服务器解析。ajax

使用Ajax发送GET请求很是简单,代码以下:服务器

function GetRequest(){函数

    var xhr = null;对象

    if(window.XMLHttpRequest){get

         xhr = new XMLHttpRequest();回调函数

    }else{it

         xhr = new ActiveXObject("Microsoft.XMLHttp");io

    }function

    xhr.open('get’,’/ajax_demo?username=itxdl&password=123456’,true);请求

    xhr.onreadystatechange = function(){

         if(xhr.readyState == 4 && xhr.status == 200){

              var data = xhr.responseText;

         }

    }

    xhr.send(null);

}

总结:

●  建立XHR对象var xhr = new XMLHttpRequest()或var xhr = new ActiveXObject ("Microsoft.XMLHttp")。

●  创建HTTP链接 xhr.open('GET’,URL,ASYNC)。

●  给XHR状态绑定一个回调函数 xhr.onreadystatechange = function(){}。

●  在回调函数中判断Ajax的状态是否等于4,HTTP状态码是否等于200,而后编写相应的业务逻辑。

●  发送一个HTTP请求 xhr.send(null);使用GET请求时send方法参数为null,若是传值的话,服务器也不会接受。

相关文章
相关标签/搜索