cryRoom

Ajax是一种使用javascript内置对象向服务器发送请求/接收响应的技术。它可以再页面已经完全显示出来之后再和服务器进行少量的数据交互,所以可以实现局部内容的刷新。

ajax的实现,主要是靠javascript中的内置对象XMLHttpRequest。它可以向服务器发送请求并接收服务器的响应。

 

下面给给出两个简单的例子:

Get方式发送请求:

         //浏览器端    
         var xhr = new XMLHttpRequest;
         xhr.open(\'get\', \'./bb.php?id=4\');
         xhr.send();
         xhr.onreadystatechange = function() {
                  if(xhr.readyState == 4 && xhr.status == 200)  //响应完成并且响应码为200
                  alert(xhr.responseText);
         }

       //服务器端
         //example.php
         <?php
         echo \'欢迎\' . $_GET[\'id\'];

 

POST方式发送请求:

//前端
var xhr = new XMLHttpRequest;
xhr.open(\'post\', \'./example.php\');
xhr.setRequestHeader(\'Content-Type\', \'application/x-www-form-urlencoded\');
xhr.send(\'id=4&num=5\');
xhr.onreadystatechange = function() {
         if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status ==304))  //响应完成并且响应码为200或304
         alert(xhr.responseText);
}

//后端
//example.php
<?php
echo \'欢迎\'. $_POST[\'id\'];
echo \'欢迎\'. $_POST[\'num\'];

 

最后说一个关于AJAX的兼容问题,在低版本的IE下,是不存在XMLHttpRequest这个内置对象的,我们使用另一个对象ActiveXObject(‘Microsoft.XMLHTTP’)替代。兼容写法如下:

var request;
if(XMLHttpRequest) {
    request = new XMLHttpRequest;
}else {
    request = new ActiveXObject(“Microssoft.XMLHTTP”);
}

  

分类:

技术点:

相关文章:

  • 2021-11-06
  • 2021-11-06
  • 2021-11-06
  • 2021-11-06
  • 2022-12-23
  • 2022-12-23
  • 2021-11-06
猜你喜欢
  • 2021-11-06
  • 2021-11-06
  • 2021-12-07
  • 2021-09-09
  • 2021-11-05
  • 2021-11-30
相关资源
相似解决方案