zoukankan      html  css  js  c++  java
  • ajax_01【httpRequest.responseText】

    AJAX的两个主要功能使您可以执行以下操作:

    • 向服务器发出请求,而无需重新加载页面
    • 从服务器接收和处理数据

    一、发出HTTP请求:

    例子:

    <button id="ajaxButton" type="button">Make a request</button>
    
    <script>
    (function() {  var httpRequest;document.getElementById("ajaxButton").addEventListener('click', makeRequest);
       //单击按钮,调用makeRequest()函数
      function makeRequest() {
       //1、向服务器发出请求
        httpRequest = new XMLHttpRequest();
       //
        if (!httpRequest) {
          alert('Giving up :( Cannot create an XMLHTTP instance');
          return false;
        }
       //2、请求后,收到回复前,设置onreadystatechange对象属性,来告诉XMLHttp请求对象哪个JavaScript函数将处理响应,
        httpRequest.onreadystatechange = alertContents;
       //3、收到响应后,再调用HTTP请求对象open()send()方法来实际发出请求,// open('请求类型','URL',可选|请求是否异步(默认true))
        httpRequest.open('GET', 'test.html');
    //send()方法的参数可以是POST-ing请求时要发送到服务器的任何数据,如果要进行post数据处理,
        //httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
         httpRequest.send(); }  

    //处理响应函数

    function alertContents() {
    //4、检查请求状态,如状态的值为xml...DONE,表已收到完整的服务器响应

    if (httpRequest.readyState === XMLHttpRequest.DONE) {
    //5、检查HTTP响应状态码

    if (httpRequest.status === 200) {
    ///6、对服务器发送的数据进行操作,需要两个方法:
    // httpRequest.responseText –以文本字符串形式返回服务器响应 // httpRequest.responseXML–将响应作为XMLDocument可以使用JavaScript DOM函数遍历的对象返回
    alert(httpRequest.responseText); }
    else { alert('There was a problem with the request.'); } } } })(); </script>

     2)如果发送通信错误:

    onreadystatechange在访问响应状态时方法中将引发异常 (请求后,回复前,在此阶段设置onreadystatechange对象属性并在请求更改状态时调用该函数后命名)

    function alertContents() {
      //
      try {
           //
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
          if (httpRequest.status === 200) {
            alert(httpRequest.responseText);
          } else {
            alert('There was a problem with the request.');
          }
        }
      }
      //
      catch( e ) {
          //
        alert('Caught Exception: ' + e.description);
      }
    }
  • 相关阅读:
    解决webstorm中vue语法没有提示
    Vue.js devtool插件下载安装及后续问题解决
    一张900w的数据表,怎么把原先要花费17s执行的SQL优化到300ms?
    liunx启动出现 pcntl_fork() has been disabled for security reasons
    【转】linux防火墙配置
    PHP-mysqli 出错回显
    【转】msfvenom使用指南
    【转】验证码绕过
    Windows提权与开启远程连接
    【转】kali安装w3af
  • 原文地址:https://www.cnblogs.com/a1-top/p/14069687.html
Copyright © 2011-2022 走看看