• AJAX基础!


    异步js和xml,页面不整个刷新的情况下发送http请求和处理回应

    原理

    XMLHttpRequest对象,是一个js对象

    在高级浏览器,直接new XMLHttpRequest创建,在老版本的IE上用ActiveX对象创建new ActiveXObject("Microsoft.XMLHTTP")

    发送请求的方法

    方法 
    描述

    open(method,url,async)

    规定请求的类型、URL 以及是否异步处理请求。

    • method:请求的类型;GET 或 POST
    • url:文件在服务器上的位置
    • async:true(异步)或 false(同步)

    send(string)

    将请求发送到服务器。

    • string:仅用于 POST 请求

    方法 
    描述

    setRequestHeader(header,value)

    向请求添加 HTTP 头。

    • header: 规定头的名称
    • value: 规定头的值

    像表单一样提交数据

    xmlhttp.open("POST","ajax_test.asp",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("fname=Bill&lname=Gates");
    getAllResponseHeaders()
    DOMString getAllResponseHeaders();

    Returns all the response headers as a string, or null if no response has been received. Note: For multipart requests, this returns the headers from the current part of the request, not from the original channel.

    getResponseHeader()
    DOMString? getResponseHeader(DOMString header);

    Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.

    Async=true
    需要提前设置响应函数
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","test1.txt",true);
    xmlhttp.send();
    Async=false
    直接放在send方法之后处理响应
    xmlhttp.open("GET","test1.txt",false);
    xmlhttp.send();
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    服务器响应

    属性 
    描述

    responseText 
    获得字符串形式的响应数据。

    responseXML 
    获得 XML 形式的响应数据。

    属性 
    描述

    onreadystatechange 
    存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

    readyState

    存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

    • 0: 请求未初始化
    • 1: 服务器连接已建立
    • 2: 请求已接收
    • 3: 请求处理中
    • 4: 请求已完成,且响应已就绪

    status

    200: "OK"

    404: 未找到页面

  • 相关阅读:
    Javascript 获得数组中相同或不同的数组元素   
    Java IO流 FileOutputStream、FileInputStream的用法   
    你的项目中使用过哪些JSTL标签?
    JavaWeb代码复用
    软件质量保证体系是什么
    二叉树的递归遍历框架:
    二叉树节点的定义框架:
    SQL 2012 Always On 为 MSCRMSqlClrLogin SQL 登录名创建非对称密钥时报语法错误
    linux命令指usermod(管理用户以及权限的命令)
    Dynamics CRM 2013 SP1 升级到Dynamics CRM 2015
  • 原文地址:https://www.cnblogs.com/ws3366/p/3716438.html
Copyright © 2020-2023  润新知