AJAX - 向服务器发送请求

AJAX - 向服务器发送一个请求

要想把请求发送到服务器,我们就需要使用 open() 方法和 send() 方法。

open() 方法需要三个参数:

  第一个参数定义发送请求所使用的方法(GET 还是 POST)。

与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。

然而,在以下情况中,请使用 POST 请求:

无法使用缓存文件(更新服务器上的文件或数据库)向服务器发送大量数据(POST 没有数据量限制)发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

  第二个参数规定服务器端脚本的 URL(该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务))。

  第三个参数规定应当对请求进行异步地处理(true(异步)或 false(同步))。

send() 方法可将请求送往服务器。如果我们假设 HTML 文件和 ASP 文件位于相同的目录,那么代码是这样的:

xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);


GET 还是 POST?

与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。

然而,在以下情况中,请使用 POST 请求:

无法使用缓存文件(更新服务器上的文件或数据库)向服务器发送大量数据(POST 没有数据量限制)发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

一个简单的 GET 请求:

xmlhttp.open("GET","demo_get.html",true);
xmlhttp.send();

您可能得到的是缓存的结果。

为了避免这种情况,请向 URL 添加一个唯一的 ID:

xmlhttp.open("GET","demo_get.html?t=" + Math.random(),true);
xmlhttp.send();

如果您希望通过 GET 方法发送信息,请向 URL 添加信息:

xmlhttp.open("GET","demo_get2.html?fname=Henry&lname=Ford",true);
xmlhttp.send();

完整代码:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
    xmlhttp.send();
}
</script>
</head>
<body>
    <h2>AJAX</h2>
    <button type="button" onclick="loadXMLDoc()">请求数据</button>
    <div id="myDiv"></div>
</body>
</html>

一个简单 POST 请求:

xmlhttp.open("POST","demo_post.html",true);
xmlhttp.send();

如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据

xmlhttp.open("POST","ajax_test.html",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

语法:

setRequestHeader(header,value)          向请求添加 HTTP 头。

header: 规定头的名称

value: 规定头的值

完整代码:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
    <h2>AJAX</h2>
    <button type="button" onclick="loadXMLDoc()">Request data</button>
    <div id="myDiv"></div>
</body>
</html>

url - 服务器上的文件

open() 方法的 url 参数是服务器上文件的地址:

xmlhttp.open("GET","ajax_test.html",true);

该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)。

异步 - True 或 False?

AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。

XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true:

xmlhttp.open("GET","ajax_test.html",true);

对于 web 开发人员来说,发送异步请求是一个巨大的进步。很多在服务器执行的任务都相当费时。AJAX 出现之前,这可能会引起应用程序挂起或停止。

通过 AJAX,JavaScript 无需等待服务器的响应,而是:

在等待服务器响应时执行其他脚本当响应就绪后对响应进行处理

Async=true

当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Async = false

如需使用 async=false,请将 open() 方法中的第三个参数改为 false:

xmlhttp.open(&quot;GET&quot;,&quot;test1.txt&quot;,false);

我们不推荐使用 async=false,但是对于一些小型的请求,也是可以的。

请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。

注意:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:

xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

实例:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>实例</title>
    <script>
        window.onload = function() {
            var oBtn = document.getElementById('btn');
            oBtn.onclick = function() {
                var xhr = null;
                if(window.XMLHttpRequest){
                    xhr = new XMLHttpRequest();
                }else{
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }
                xhr.open('get','new.php',true); //引入new.php文件
                xhr.send();
                xhr.onreadystatechange = function() {
                    if ( xhr.readyState == 4 ) {
                        if ( xhr.status == 200 ) {
                        //alert( xhr.responseText ); 后端传来的格式是一个数组里面很多条json 自己可以测试下
                           var data = JSON.parse( xhr.responseText ); // 将后台获取的内容转为json类型 每一个json里面有两个键:title和date
                           var oUl = document.getElementById('ul1'); //获取显示新闻列表的节点
                           var html = '';
                           for (var i=0; i<data.length; i++) { // 循环所有的json数据,并把每一条添加到列表中
                              html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>';
                           }
                            oUl.innerHTML = html; //把内容放在页面里
                        } else {
                            alert('出错了,Err:' + xhr.status);
                        }
                    }
                }
            }
        }
    </script>
</head>
<body>
    <input type="button" value="按钮" id="btn" />
    <ul id="ul1"></ul>
</body>
</html>

创建一个new.php文件:

<?php
  header('content-type:text/html;charset="utf-8"');
  error_reporting(0);
    $news = array(
      array('title'=>'女总理默克尔滑雪时摔倒 骨盆断裂','date'=>'2014-1-6'),
      array('title'=>'驻英外交官撰文互称对方国家为"伏地魔"','date'=>'2014-1-6'),
      array('title'=>'安倍:望与中国领导人会面 中方:你关闭了大门','date'=>'2014-1-6'),
      array('title'=>'揭秘台湾驻港间谍网运作 湖北宜昌副市长被查','date'=>'2014-1-6'),
      array('title'=>':嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'),
    );
    echo json_encode($news);
?>


继续学习
||
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>实例</title> <script> window.onload = function() { var oBtn = document.getElementById('btn'); oBtn.onclick = function() { var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open('get','/asset/demo.ajax.php?dm=json&act=getnews',true); //引入new.php文件 xhr.send(); xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { //alert( xhr.responseText ); 后端传来的格式是一个数组里面很多条json 自己可以测试下 var data = JSON.parse( xhr.responseText ); // 将后台获取的内容转为json类型 每一个json里面有两个键:title和date var oUl = document.getElementById('ul1'); //获取显示新闻列表的节点 var html = ''; for (var i=0; i<data.length; i++) { // 循环所有的json数据,并把每一条添加到列表中 html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>'; } oUl.innerHTML = html; //把内容放在页面里 } else { alert('出错了,Err:' + xhr.status); } } } } } </script> </head> <body> <input type="button" value="按钮" id="btn" /> <ul id="ul1"></ul> </body> </html>
提交重置代码
高并发千万级数据库系统解决方案
  • 推荐课程
  • 评论
  • 问答
  • 笔记
  • 课件下载

面对疾风吧

有的知识点出现的很突然,让我措手不及,然后。。。就不会了。

7年前    添加回复 1

末日的春天

求最简单的方式

7年前    添加回复 0

学习ing

左边字好多啊,看着眼睛好累

7年前    添加回复 0

素颜

代码有点多,感觉有点蒙了

7年前    添加回复 0

Alway.以为

很不错的内容啊,很赞

7年前    添加回复 0

课件暂不提供下载,工作人员正在整理中,后期请多关注该课程~