• ajax


    ajax

    ajax即Asynchronous Javascript And XML不是一门云烟,而是对现有技术的综合利用。本质是在HTTP协议的基础上以异步的
    方式与服务器进行同行

    异步:值某段程序执行时不会阻塞其他程序执行,其表现形式为程序的执行顺序不依赖程序本身的书写顺序

    XMLHttpRequest对象
    浏览器内建对象,用于在后台与服务器通信(交换数据),有次可以实现对网页的部分更新,而不是舒心整个页面

    所有现代浏览器都有XMLHttpRequest对象
    var xhr = new XMLHttpRequest()

    老板的Internet Explorer(IE5和IE6)使用ActiveXObject
    var xhr = new ActiveXObject(Microsoft.XMLHTTP);

    如需将请求发送到服务器,我们使用XMLHttpRequest对象的open()和send()方法

    var  xhr = new XMLHttpRequest();
    xhr.open("GET",'ajax_info.json',true);
    xhr.send();
    
    方法 描述
    open(method,url,async) 规定请求的类型、URL以及是否异步处理请求。method:请求类型GET或POST url:文件在服务器上的位置 async:true(异步)、false(同步)
    sed(string) 将请求发送到服务器。string:仅用于POST请求

    get请求

    get请求参数需要放在url地址的参数中。并通过urlencode的方式传参,也就是?隔开url和参数,然后多个参数用&链接,参数格式为:key=val

    var xhr = new XMLHttpRequest();
    xhr.open("GET","/ajax.php?fname=Henry&name=ff",true)
    xhr.send()
    

    post请求

    post请求需要添加一个请求头,让后台知道我们请求的参数格式,这样后台才能解析我们数据。另外,传输的数据需要格式化到send方法中

    var xhr = new XMLHttpRequest();
    xhr.open("POST","/AJAX.PHP",true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send("fname=henery&name=Ford");
    

    接受数据并处理数据

    XMLHttpRequest对象的相关属性和事件

    属性 说明
    status 200:"OK"
    responseText 获得字符串形式的相应数据
    responseXML 获得XML形式的形影数据
    readyState 存有XMLHttpRequest的状态。请求发送到后台后,状态从0到4发生变化。0-请求未初始化1-服务器连接已建立2-请求已接收3-请求处理中4-请求已完成,且响应已就绪
    onreadystatechange 每当readyState属性改变时,就会调用这个函数

    我们可以通过调用XMLHttpRequest对象的onreadystatechange时间,在时间的回调函数中判断readyState的状态

    例子

    get请求

    //ajax
    //get
    var xhr = new XMLHttpRequest();
    xhr.open("GET","https://cnodejs.org/api/v1/topics",true);
    xhr.send();
    xhr.onreadystatechange = function(e){
    	console.log(xhr);
    	if(xhr.readyState===4 && xhr.status === 200){
    		console.log(xhr.responseText);
    		console.log("=================responseXML================");
    		console.log(xhr.responseXML)
    	}
    }
    

    post请求

    var xhr = new XMLHttpRequest();
    xhr.open("POST","/api/getmsg",true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send("name=33&ks=44");
    xhr.onreadystatechange = function(e){
    	if(xhr.readyState === 4 && xhr.status === 200){
    		console.log(xhr.resonseText);
    	}
    }
    
  • 相关阅读:
    Caused by: Unable to load bean: type: class:com.opensymphony.xwork2.ObjectFactory
    nable to load bean: type:com.opensymphony.xwork2.util.ValueStackFactory
    一个web项目web.xml的配置中<context-param>配置作用
    js获取form的方法
    HTML <legend> 标签
    Struts2 文件上传 之 文件类型 allowedTypes
    Struts2验证框架的配置及validation.xml常用的验证规则
    struts2学习笔记--使用Validator校验数据
    LeetCode204:Count Primes
    《采访中收集程序猿》学习记录5
  • 原文地址:https://www.cnblogs.com/dehenliu/p/12523532.html
Copyright © 2020-2023  润新知