JAVA Web学习(19)___第13章Ajax技术

2019-10-12  本文已影响0人  岁月静好浅笑安然

第13章Ajax技术

13.1 当下谁使用Ajax

百度搜索提示、淘宝新会员注册

13.2 Ajax开发模式与传统模式比较

传统的web应用模式中,将生成一次HTTP请求,而在Ajax应用开发模式中,将变成对Ajax引擎的一次JavaScript调用,不需要整个页面刷新,对部分数据进行更新,从而降低网络流量,给用户带来更好的体验。

13.3 Ajax的使用技术

13.4 使用XMLHttpRequest对象

13.4.1 初始化 XMLHttpRequest对象

    var httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
    或者
    var httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
    var httpRequest=new XMLHttpRequest();
var httpRequest; 
if(window.XMLHttpRequest){
    httpRequest=new XMLHttpRequest(); //非IE浏览器
}else if(window.ActiveXObject){       //IE浏览器           
    try{
    httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
    try{
    httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
    }catch(e){
    }
    }
}

13.4.2 XMLHttpRequest对象的常用方法

    open("method","URL"[,asyncFlag[,"username"[,"password"]]]])

参数说明

    httpRequest.open("GET","reqister.jsp",true);
    send(content)

参数说明:
content:用于指定发送的数据,可以是DOM对象的实例、输入流或字符串,如果没有参数需要传递,可以设置为null

 setRequestHeader("header","value")

setRequestHeader()方法必须在调用open()方法之后才能调用
示例代码

    httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    getResponseHeader("headerLabel")

参数说明:headerLabel用于指定HTTP头,包括Server、Content-Type和Date等
示例代码

    httpRequest.getAllResponseHeaders("Content-Type");
    httpRequest.getAllResponseHeaders();

13.4.3 XMLHttpRequest对象的常用属性

用于指定状态发生改变时所触发的事件处理器

用于获取请求的状态

意义 意义
0 未初始化 3 交互中
1 正在加载 4 完成
2 已加载

13.5 与服务器通信--发送请求和处理响应

13.5.1 示例代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // 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","./ajax_info.txt",true);
    
    //需要在index.jsp同级目录下,新建ajax_info.txt文件,在ajax_info.txt中写入要更改的内容,点击按钮更改内容
    xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
<button type="button" onclick="loadXMLDoc()">修改内容</button>

</body>
</html>

13.6 解决中文乱码问题

13.6.1 发送请求时出现中文乱码

    String str=request.getParameter("parPorvince");
    str=new String(str.getBytes("ISO-8859-1"),"UTF-8"):

13.6.2 获取服务器的响应结果时出现中文乱码

保证从服务器端传递的数据采用UTF-8的编码格式。

13.7 Ajax重构

将通用的代码进行封装

13.8 Ajax常用实例

上一篇 下一篇

猜你喜欢

热点阅读