Ajax技术实战操练课堂学习笔记

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。更多学习资料请访问我爱科技论坛:www.52tech.tech https://blog.csdn.net/m0_37981569/article/details/78412799 ...
版权声明:本文为博主原创文章,未经博主允许不得转载。更多学习资料请访问我爱科技论坛:www.52tech.tech https://blog.csdn.net/m0_37981569/article/details/78412799

ajax是什么

  1. ajax(asynchronouse javascript and xml) 异步的javascript xml
  2. 7种技术的综合,它包含了七个技术( javascript xml xstl xhtml dom xmlhttprequest , css), ajax 是一个粘合剂,
  3. ajax是一个与服务端语言无关的技术. 即可以使用在(php/java ee/.net网站/ asp)
  4. ajax可以给客户端返回三种格式数据(文本格式 xml , json格式)
  5. 无刷新数据交换技术有以下: flash, java applet, 框架, iframe, ajax)

 

 

  • ajax 的运行原理分析

 

 

 

看一个需求:

 

  • ajax在什么地方用的多

 

1 动态加载数据,按需取得数据。【树形菜单、联动菜单.../省市联动】

2 改善用户体验。【输入内容前提示、带进度条文件上传...

 

3 电子商务应用。    【购物车、邮件订阅...

4 访问第三方服务。    【访问搜索服务、rss阅读器】

5. 数据的布局刷新

 

  • 经典的案例

 

使用ajax与服务器通信的的步骤

  1. 创建一个XMLHttpRequest对象
  2. 创建url, data,通过 xmlHttpRequest.send()
  3. 服务器端接收 ajax的请求,做相应处理(操作数据库),然后返回结果(echo 语句)
  4. 客户端通过xmlHttpRequest的属性 reponseText , responseXML 取的数据,然后就完成局部刷新当前页面任务

 

使用 ajax完成用户名的验证(get方式提交数据)

 

register.php

 

<html>

<head>

<title>用户注册</title>

<meta http-equiv="content-type" content="text/html;charset=utf-8"/>

<script type="text/javascript">

 

    //创建ajax引擎

    function getXmlHttpObject(){

        

        var xmlHttpRequest;

        //不同的浏览器获取对象xmlhttprequest 对象方法不一样

        if(window.ActiveXObject){

            

            xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");

            

        }else{

 

            xmlHttpRequest=new XMLHttpRequest();

        }

 

        return xmlHttpRequest;

 

    }

    var myXmlHttpRequest="";

 

    //验证用户名是否存在

    function checkName(){

        

        myXmlHttpRequest=getXmlHttpObject();

 

        //怎么判断创建ok

        if(myXmlHttpRequest){

            

            //通过myXmlHttpRequest对象发送请求到服务器的某个页面

            //第一个参数表示请求的方式, "get" / "post"

            //第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)

            //第三个参数表示 true表示使用异步机制,如果false表示不使用异步

            var url="/ajax/registerProcess.php?mytime="+new Date()+"&username="+$("username").value;

            //打开请求.

            myXmlHttpRequest.open("get",url,true);

            //指定回调函数.chuli是函数名

            myXmlHttpRequest.onreadystatechange=chuli;

 

            //真的发送请求,如果是get请求则填入 null即可

            //如果是post请求,则填入实际的数据

            myXmlHttpRequest.send(null);

 

 

        }

    }

 

    //回调函数

    function chuli(){

        

        //window.alert("处理函数被调回"+myXmlHttpRequest.readyState);

        //我要取出从registerPro.php页面返回的数据

        if(myXmlHttpRequest.readyState==4){

            

            //取出值,根据返回信息的格式定.text

            //window.alert("服务器返回"+myXmlHttpRequest.responseText);

 

            $('myres').value=myXmlHttpRequest.responseText;

        }

    }

 

    //这里我们写一个函数

    function $(id){

        return document.getElementById(id);

    }

</script>

</head>

<body>

    <form action="???" method="post">

用户名字:<input type="text" onkeyup="checkName();" name="username1" id="username"><input type="button" onclick="checkName();" value="验证用户名">

<input style="border-width: 0;color: red" type="text" id="myres">

<br/>

用户密码:<input type="password" name="password"><br>

电子邮件:<input type="text" name="email"><br/>

<input type="submit" value="用户注册">

</form>

<form action="???" method="post">

用户名字:<input type="text" name="username2" >

 

<br/>

用户密码:<input type="password" name="password"><br>

电子邮件:<input type="text" name="email"><br/>

<input type="submit" value="用户注册">

</form>

 

</body>

</html>

 

 

registerpro.php

 

<?php

    

    //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

    header("Content-Type: text/xml;charset=utf-8");

    //告诉浏览器不要缓存数据

    header("Cache-Control: no-cache");

 

    //接收数据

    $username=$_GET['username'];

 

 

    if($username=="shunping"){

        echo "用户名不可以用";//注意,这里数据是返回给请求的页面.

    }else{

        echo "用户名可以用";

    }

 

      

    

 

?>    

【相关代码】

Login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>注册页面</title>

 

 

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

<script type="text/javascript" src="myscripts.js" charset="UTF-8"></script>

<script type="text/javascript" src="js/ajax.js" charset="UTF-8"></script>

</head>

 

<body>

    <center>

 

        <form action="" method="post">

            用户名:<input type="text" name="username1" id="username" onkeyup="checkName()"/><input

                type="button" value="验证用户名" onclick="checkName()" /> <input

                style="border-width: 0; color:red; font-size: 20px; font-weight: bold;" type=text id="myres" readonly="readonly"/><br />

            用户密码:<input type="password" name="password" /><br /> 电子邮件: <input

                type="text" name="email" /><br /> <input type="submit"

                value="用户注册" />

        </form>

        <form action="" method="post">

            用户名:<input type="text" name="username1" id="username" /><input

                type="button" value="验证用户名" /><br /> 用户密码:<input type="password"

                name="password" /><br /> 电子邮件: <input type="text" name="email" /><br />

            <input type="submit" value="用户注册" />

        </form>

    </center>

</body>

</html>

 

LoginchuLiServlet.java

package com.web.view;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class LoginChuLiServlet extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html; charset=utf-8");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        

        //禁用缓存

        response.setDateHeader("Expires", -1);

 

        

        //接受数据

        String uname = request.getParameter("username");

        System.out.println("username is "+uname);

        //out.write(uname);

        //把数据返回出去

        //response.sendRedirect("http://www.baidu.com");

        //request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

        //*request.setAttribute("name", "color");

        //利用该方法可以向浏览器返回数据

        //out.print("123456789");

        if ("admin".equals(uname))

        {

            out.println("用户名正确");

        }

        else

        {

            out.println("用户名不可用");

        }

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

 

}

 

Ajax.js

//创建Ajax引擎

function getXmlHttpRequest() {

    var xmlHttpRequest;

    // 不同的浏览器获取XmlHttpRequest的方法是不一样的

    if (window.ActiveXObject) {

        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        // window.alert("ie");

    } else {

        xmlHttpRequest = new XMLHttpRequest();

        // window.alert("huohu");

    }

    return xmlHttpRequest;

}

 

//全局变量

var myXmlHttpRequest = "";

function checkName() {

    myXmlHttpRequest = getXmlHttpRequest();

    // 判断是否创建成功

    if (myXmlHttpRequest != null) {

        //window.alert("创建Ajax引擎成功!");

        // 通过myXmlHttpRequest对象发送请求到服务器的某一个页面

        

        //方案一:通过增加一个时间变量让浏览器可以刷新

        var url = "/AjaxProject/LoginChuLiServlet?time="+new Date()+"&username="

                + $("username").value;

        //方案二:通过设置浏览器禁用缓存来刷新页面

         url = "/AjaxProject/LoginChuLiServlet?username="

            + $("username").value;

        

        //window.alert(url);

        // true表示使用异步机制(打开请求)

        //1.get/post 2.对那个页面使用Ajax 3.是否使用异步机制

        myXmlHttpRequest.open("get", url, true);

        // 指定回调函数, chuli是函数名称

        myXmlHttpRequest.onreadystatechange = chuli;

        

        //真的发送请求, get请求填入null即可; post请求要填入实际的数据

        myXmlHttpRequest.send(null);

    } else {

        window.alert("创建Ajax引擎失败!");

    }

}

 

//回调函数

function chuli(){

    //window.alert("处理函数被调回"+myXmlHttpRequest.readyState);

    //取出从LoginChuLi返回的数值

    if (myXmlHttpRequest.readyState == 4){

        //4表示已完成的状态

        //根据返回信息的格式取出值

        //window.alert("服务器返回了数据"+myXmlHttpRequest.responseText);

        $("myres").value = myXmlHttpRequest.responseText;

    }

        

}

 

 

function $(id) {

    return document.getElementById(id);

}

 

ajaxpost方式请求

【关键代码: Ajax.js

function checkName() {

    myXmlHttpRequest = getXmlHttpRequest();

    // 判断是否创建成功

    if (myXmlHttpRequest != null) {

        // window.alert("创建Ajax引擎成功!");

        // 通过myXmlHttpRequest对象发送请求到服务器的某一个页面

        // 方案一:通过增加一个时间变量让浏览器可以刷新

        var url = "/AjaxProject/LoginChuLiServlet?time=" + new Date()

                + "&username=" + $("username").value;

        // 方案二:通过设置浏览器禁用缓存来刷新页面

        url = "/AjaxProject/LoginChuLiServlet?username=" + $("username").value;

        // 使用post方式来提交数据

        var url2 = "/AjaxProject/LoginChuLiServlet";

        var data = "username="+$("username").value;

        // window.alert(url);

        // true表示使用异步机制(打开请求)

        // 1.get/post 2.对那个页面使用Ajax 3.是否使用异步机制

        //myXmlHttpRequest.open("get", url, true);

        

        //post提交

        myXmlHttpRequest.open("post", url2, true);

//这行代码不能少        myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        

        // 指定回调函数, chuli是函数名称

        myXmlHttpRequest.onreadystatechange = chuli;

        // 真的发送请求, get请求填入null即可; post请求要填入实际的数据

        //myXmlHttpRequest.send(null);

        

        myXmlHttpRequest.send(data);

    } else {

        window.alert("创建Ajax引擎失败!");

    }

}

在前面案例我们修改一下

 

 

关键代码

register.php

var url="/ajax/registerProcess.php";

            //这个是要发送的数据

            var data="username="+$('username').value;

            //打开请求.

            myXmlHttpRequest.open("post",url,true);

            //还有一句话,这句话必须.

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

            //指定回调函数.chuli是函数名

            myXmlHttpRequest.onreadystatechange=chuli;

 

            //真的发送请求,如果是get请求则填入 null即可

            //如果是post请求,则填入实际的数据

            myXmlHttpRequest.send(data);

registerPro.php关键码

$username=$_POST['username'];

 

 

使用get方式发出请求,如果提交的用户名不变化,浏览器将不会真的发请求,而是缓存取数据., url

 

解决方法

  1. url 后带一个总是变化的参数,比如当前时间

var url="/ajax/registerProcess.php?mytime="+new Date()+"&username="+$("username").value;

 

  1. 在服务器回送结果时,禁用缓存.

 

//这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

    header("Content-Type: text/xml;charset=utf-8");

    //告诉浏览器不要缓存数据

    header("Cache-Control: no-cache");

  • 有些网站要求及时性很高,因此要求我们不缓存页面

代码:(以下代码适用于股票、基金等即时性网站, 取消浏览器缓存)

//指定该页面不缓存 Ie

        response.setDateHeader("Expires", -1);【针对IE浏览器设置不缓存】

        //为了保证兼容性.

        response.setHeader("Cache-Control", "no-cache");【针对火狐浏览器等】

        response.setHeader("Pragma", "no-cache");【其他浏览器】

  • 有些网站要求网页缓存一定时间,比如缓存一个小时(1h=3600s; 1s=1000ms; 1d=24h;

response.setDateHeader("Expires", System.currentTimeMillis()+3600*1000);后面一个参数表示设置的缓存保持时间,-1表示永远缓存

 

        //方案一:通过增加一个时间变量让浏览器可以刷新

        var url = "/AjaxProject/LoginChuLiServlet?time="+new Date()+"&username="

                + $("username").value;

        //方案二:通过设置浏览器禁用缓存来刷新页面

         url = "/AjaxProject/LoginChuLiServlet?username="

            + $("username").value;

 

//实现对用户名的即时验证:

            用户名:<input type="text" name="username1" id="username" onkeyup="checkName()"/><input

                type="button" value="验证用户名" onclick="checkName()" />

 

 

ajax如何处理返回的数据格式是xml的情况

 

register.php

 

<html>

<head>

<title>用户注册</title>

<meta http-equiv="content-type" content="text/html;charset=utf-8"/>

<script type="text/javascript">

 

    //创建ajax引擎

    function getXmlHttpObject(){

        

        var xmlHttpRequest;

        //不同的浏览器获取对象xmlhttprequest 对象方法不一样

        if(window.ActiveXObject){

            

            xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");

            

        }else{

 

            xmlHttpRequest=new XMLHttpRequest();

        }

 

        return xmlHttpRequest;

 

    }

    var myXmlHttpRequest="";

 

    //验证用户名是否存在

    function checkName(){

        

        myXmlHttpRequest=getXmlHttpObject();

 

        //怎么判断创建ok

        if(myXmlHttpRequest){

            

            //通过myXmlHttpRequest对象发送请求到服务器的某个页面

            //第一个参数表示请求的方式, "get" / "post"

            //第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)

            //第三个参数表示 true表示使用异步机制,如果false表示不使用异步

            var url="/ajax/registerProcess.php";

            //这个是要发送的数据

            var data="username="+$('username').value;

            //打开请求.

            myXmlHttpRequest.open("post",url,true);

            //还有一句话,这句话必须.

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

            //指定回调函数.chuli是函数名

            myXmlHttpRequest.onreadystatechange=chuli;

 

            //真的发送请求,如果是get请求则填入 null即可

            //如果是post请求,则填入实际的数据

            myXmlHttpRequest.send(data);

 

 

        }

    }

 

    //回调函数

    function chuli(){

        

        //window.alert("处理函数被调回"+myXmlHttpRequest.readyState);

        //我要取出从registerPro.php页面返回的数据

        if(myXmlHttpRequest.readyState==4){

            

            //取出值,根据返回信息的格式定.text

            //window.alert("服务器返回"+myXmlHttpRequest.responseText);

 

            //$('myres').value=myXmlHttpRequest.responseText;

 

            //看看如果取出 xml格式数据

            //window.alert(myXmlHttpRequest.responseXML);

        

            //获取mes节点

            var mes=myXmlHttpRequest.responseXML.getElementsByTagName("mes");

 

            //取出mes节点值

            //window.alert(mes.length);

            //mes[0]->表示取出第一个mes节点

            //mes[0].childNodes[0]->表示第一个mes节点的第一个子节点

            var mes_val=mes[0].childNodes[0].nodeValue;

 

            $('myres').value=mes_val;

        }

    }

 

    //这里我们写一个函数

    function $(id){

        return document.getElementById(id);

    }

</script>

</head>

<body>

    <form action="???" method="post">

用户名字:<input type="text" name="username1" id="username"><input type="button" onclick="checkName();" value="验证用户名">

<input style="border-width: 0;color: red" type="text" id="myres">

<br/>

用户密码:<input type="password" name="password"><br>

电子邮件:<input type="text" name="email"><br/>

<input type="submit" value="用户注册">

</form>

<form action="???" method="post">

用户名字:<input type="text" name="username2" >

 

<br/>

用户密码:<input type="password" name="password"><br>

电子邮件:<input type="text" name="email"><br/>

<input type="submit" value="用户注册">

</form>

 

</body>

</html>

 

 

regisgerProcess.php

 

<?php

    

    //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

    header("Content-Type: text/xml;charset=utf-8");

    //告诉浏览器不要缓存数据

    header("Cache-Control: no-cache");

 

    //接收数据(这里要和请求方式对于 _POST 还是 _GET)

    $username=$_POST['username'];

 

    //这里我们看看如何处理格式是xml

    $info="";

    if($username=="shunping"){

        $info.="<res><mes>用户名不可以用,对不起</mes></res>";//注意,这里数据是返回给请求的页面.

    }else{

        $info.="<res><mes>用户名可以用,恭喜</mes></res>";

    }

 

    echo $info;

    

 

?>    

    // window.alert("处理函数被调回"+myXmlHttpRequest.readyState);

    // 取出从LoginChuLi返回的数值

    if (myXmlHttpRequest.readyState == 4) {

        // 4表示已完成的状态

        // 根据返回信息的格式取出值

        // window.alert("服务器返回了数据"+myXmlHttpRequest.responseText);

        // $("myres").value = myXmlHttpRequest.responseText;

 

        // 开始取出XML格式数据, myXmlHttpRequest.responseXML取出的是一个dom对象

        // 这里涉及XMLDomHtmlDom编程

        // $("myres").value = myXmlHttpRequest.responseXML;

        //window.alert("testing ");

//利用JavaScriptdom编程可解决

        // 获取mes节点, 注意getElementsByTagName不要写错了

        var mes = myXmlHttpRequest.responseXML.getElementsByTagName("mes");

        if (mes != null) {

            

        }

        //获取节点下面的数值

        //mes[0]表示取出第一个mes节点

        //mes[0].childNodes[0]表示取出第一个 mes节点下面的第一个子节点

        var mes_val = mes[0].childNodes[0].nodeValue;

        //window.alert(mes_val);

         $("myres").value = mes_val;

    }

 

 

// 1.开始处理返回内容是xml的格式; text/xml

response.setContentType("text/xml; charset=utf-8");

        if ("admin".equals(uname)) {

            // out.println("用户名正确");

            out.println("<res><mes>用户名已注册, 换个用户名吧</mes></res>");

        } else {

            out.println("<res><mes>共黑你, 用户名可以用!</mes></res>");

        }

 

ajax如何处理json数据格式

 

 

json的格式如下

 

"{属性名:属性值,属性名:属性值,.... }"

因为json数据是原生态数据,因此这种数据格式很稳定,而且描述能力强,我们建议大家使用json格式

<script type="text/javascript">

    var dog = {"name":"dog", "color":"red"};

 

    //window.alert(typeof dog);

    window.alert(dog.name);

    window.alert(dog.color);

 

</script>

 

        //2.处理Json数据格式, 也要设置成为文本格式

        response.setContentType("text/html; charset=utf-8");

if ("admin".equals(uname)) {

            // out.println("用户名正确");

            //out.println("<res><mes>用户名已注册, 换个用户名吧</mes></res>");

            

            //返回json格式代码数据, value是一个json数据格式的子串

            String value = "{\"res\":\"该用户不可以使用!!!\"}";

            String aaa = "{'res':'该用户不可以使用才怪呢!!!', 'id':'001'}";

            out.println(aaa);

            

        } else {

            //out.println("<res><mes>共黑你, 用户名可以用!</mes></res>");

            //String value = "{\"res\":\"该用户可以使用!!!\"}";

            String value = "{'res':'该用户是可以使用滴!', 'id':'002'}";

            out.println(value);

        }

 

 

    if (myXmlHttpRequest.readyState == 4) {

        

        //开始获取json格式的子串

        var mes_val = myXmlHttpRequest.responseText;

        //window.alert(typeof mes_val); //String格式

        //使用eval函数讲mes_val转换成对应的对象

        var mes_obj = eval("("+mes_val+")"); //object对象

        //window.alert(typeof mes_obj);

         $("myres").value = mes_obj.res+"错误码:"+mes_obj.id;

    }

json数据格式的扩展

如果服务器返回的json 是多组数据,则格式应当如下:

 

$info="[{"属性名":"属性值",...},{"属性名":"属性值",...},....]";

 

xmlhttprequest对象接收到json数据后,应当这样处理

 

 

//转成对象数组

 

var reses=eval("("+xmlHttpRequest.responseText+")");

 

//通过reses可以取得你希望的任何一个值

 

reses[?].属性名

 

        if ("admin".equals(uname)) {

            // out.println("用户名正确");

            //out.println("<res><mes>用户名已注册, 换个用户名吧</mes></res>");

            

            //返回json格式代码数据, value是一个json数据格式的子串

            String value = "{\"res\":\"该用户不可以使用!!!\"}";

            String aaa = "[{'res':'该用户不可以使用才怪呢!!!', 'id':'001'}, {'res':'不可以使用才怪呢!!!', 'id':'004'}]";

            out.println(aaa);

            

        } else {

            //out.println("<res><mes>共黑你, 用户名可以用!</mes></res>");

            //String value = "{\"res\":\"该用户可以使用!!!\"}";

            String value = "[{'res':'该用户是可以使用滴!', 'id':'002'}, {'res':'不可以使用该用户!', 'id':'003'}]";

            out.println(value);

        }

 

 

//开始获取json格式的子串

        var mes_val = myXmlHttpRequest.responseText;

        //window.alert(typeof mes_val); //String格式

        //使用eval函数讲mes_val转换成对应的对象

        var mes_obj = eval("("+mes_val+")"); //object对象

        //window.alert(typeof mes_obj);

    $("myres").value = mes_obj[1].res+"错误码:"+mes_obj[1].id;//遍历

 

 

<script type="text/javascript">

    var dog = [{"name":"dog", "color":"red"}, {"name":"dog1", "color":"blue"}, {"name":"dog3", "color":"yellow"}];

 

    //window.alert(typeof dog);

    //window.alert(dog.name);

    //window.alert(dog.color);

    //window.alert(dog[0].name+" "+dog.length);

    //window.alert(dog[1].color)

    for (var i=0; i<dog.length; i++)

    {

        window.alert(dog[i].name+" "+dog[i].color);

    }

</script>

更加复杂的json数据格式

 

<script language="JavaScript">

var people ={

"programmers":

[

{"firstName": "Brett", "email": "brett@newInstance.com" },

{"firstName": "Jason", "email": "jason@servlets.com" }

],

"writer":

            [

                {"writer":"宋江","age":"50"},

                {"writer":"吴用","age":"30"}

            ],

            "sex":""

            

};

 

 

window.alert(people.programmers[0].firstName);

window.alert(people.programmers[1].email);

 

window.alert(people.writer[1].writer);

window.alert(people.sex);

</script>

 

小结:

当一个ajax请求到服务器,服务器可以根据需求返回 三种格式的数据,那么我们应当选择哪一个?

 

  • 如果你的项目经理没有特殊的要求,建议使用json
  • 若应用程序不需要与其他应用程序共享数据的时候, 使用 HTML 片段来返回数据时最简单
  • 如果数据需要重用, JSON 文件是个不错的选择, 其在性能和文件大小方面有优势
  • 远程应用程序未知, XML 文档是首选, 因为 XML web 服务领域的 "世界语"(不知道请求是谁发出的就用xml)

 

 

ajax的省市联动案例(如何动态的从服务器取得数据)

showCities.php页面

<html>

<head>

<meta http-equiv="content-type" content="text/html;charset=utf-8"/>

<script type="text/javascript">

 

 

//创建ajax引擎

    function getXmlHttpObject(){

        

        var xmlHttpRequest;

        //不同的浏览器获取对象xmlhttprequest 对象方法不一样

        if(window.ActiveXObject){

            

            xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");

            

        }else{

 

            xmlHttpRequest=new XMLHttpRequest();

        }

 

        return xmlHttpRequest;

 

    }

 

    var myXmlHttpRequest="";

 

function getCities(){

 

    myXmlHttpRequest=getXmlHttpObject();

 

    if(myXmlHttpRequest){

        

        var url="/ajax/showCitiesPro.php";//post

        var data="province="+$('sheng').value;

 

        myXmlHttpRequest.open("post",url,true);//异步方式

 

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

 

        //指定回调函数

        myXmlHttpRequest.onreadystatechange=chuli;

 

        //发送

        myXmlHttpRequest.send(data);

    }

}

 

    function chuli(){

        if(myXmlHttpRequest.readyState==4){

            

            if(myXmlHttpRequest.status==200){

                

                //取出服务器回送的数据

 

                var cities=myXmlHttpRequest.responseXML.getElementsByTagName("city");

                

                $('city').length=0;

                var myOption=document.createElement("option");

                    

                    myOption.innerText="--城市--";

                    //添加到

                    $('city').appendChild(myOption);

 

                //遍历并取出城市

                for(var i=0;i<cities.length;i++){

                    

                    var city_name=cities[i].childNodes[0].nodeValue;

                    //创建新的元素option

                    var myOption=document.createElement("option");

                    myOption.value=city_name;

                    myOption.innerText=city_name;

                    //添加到

                    $('city').appendChild(myOption);

                }

            }

        }

    }

 

 

    //这里我们写一个函数

    function $(id){

        return document.getElementById(id);

    }

 

</script>

</head>

<body>

<select id="sheng" onchange="getCities();">

<option value="">------</option>

<option value="zhejiang">浙江</option>

<option value="jiangsu" >江苏</option>

<option value="sichuan" >四川</option>

</select>

<select id="city">

<option value="">--城市--</option>

</select>

 

<select id="county">

<option value="">--县城--</option>

</select>

 

</body>

</html>

 

**showCitiesProcess.php**

 

<?php

 

    //服务器端

 

    //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

    header("Content-Type: text/xml;charset=utf-8");

    //告诉浏览器不要缓存数据

    header("Cache-Control: no-cache");

 

 

    //接收用户的选择的省的名字

 

    $province=$_POST['province'];

 

    file_put_contents("d:/mylog.log",$province."\r\n",FILE_APPEND);

    //如何在调试过程中,看到接收到的数据

    //到数据库去查询省有那些城市(现在先不到数据库)

    $info="";

    if($province=="zhejiang"){

        

        $info="<province><city>杭州</city><city>温州</city><city>宁波</city></province>";

    }else if($province=="jiangsu"){

        $info="<province><city>南京</city><city>徐州</city><city>苏州</city></province>";

    }

        

 

    echo $info;

 

?>

 

index.js

//创建Ajax引擎

function getXmlHttpRequest() {

    var xmlHttpRequest;

    // 不同的浏览器获取XmlHttpRequest的方法是不一样的

    if (window.ActiveXObject) {

        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        // window.alert("ie");

    } else {

        xmlHttpRequest = new XMLHttpRequest();

        // window.alert("huohu");

    }

    return xmlHttpRequest;

}

 

var myXmlHttpRequest = "";

// 省市联动案例js

function getCities() {

    // window.alert("ok");

    myXmlHttpRequest = getXmlHttpRequest();

    if (myXmlHttpRequest != null) {

        // 向服务器发送请求

        var url = "/AjaxProject/CityChuLiServlet";

        var data = "province=" + $("sheng");

        // window.alert(""+data);

        myXmlHttpRequest.open("post", url, true);

        myXmlHttpRequest.setRequestHeader("Content-Type",

                "application/x-www-form-urlencoded");

 

        // 指定回调函数

        myXmlHttpRequest.onreadystatechange = chuli;

        // 发送请求

        myXmlHttpRequest.send(data);

    }

}

JavaScriptXMLDom编程和HTMLDom编程

function chuli() {

    // window.alert(myXmlHttpRequest.readyState+" "+myXmlHttpRequest.status);

    // window.alert("chuli");

    if (myXmlHttpRequest.readyState == 4 && myXmlHttpRequest.status == 200) {

        // window.alert("ok");

        // window.alert(myXmlHttpRequest.responseXML);

        var cities = myXmlHttpRequest.responseXML.getElementsByTagName("city");

        //window.alert(cities.length);

          

        

        //该方法的主要目的是把每次选择以后, city下拉框的长度清零, 防止节点累加

        document.getElementById("city").length = 0;

        

        var myoption1 = document.createElement("option");

        var str = "--城市--";

        myoption1.innerText = str;

        document.getElementById("city").appendChild(myoption1);    

        

        // 遍历取出数据

        for (var i = 0; i < cities.length; i++) {

            var city_name = cities[i].childNodes[0].nodeValue;

            //window.alert(city_name);

            //创建新的元素option

            var myoption = document.createElement("option");

            myoption.value = city_name;

            myoption.innerText = city_name;

            //添加属性到对应cityselect选项中去

            document.getElementById("city").appendChild(myoption);            

        }

    }

}

 

function $(id) {

    return document.getElementById(id).value;

}

 

 

servlet.java

package com.web.servlet;

 

import java.io.*;

 

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class CityChuLiServlet extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/xml; charset=utf-8");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        // 这里是服务器端

        String sheng = request.getParameter("province");

        

        //数据库验证

        String info = "";

        if ("zhejiang".equals(sheng))

        {

            info = "<province><city>杭州</city> <city>义乌</city> <city>金华</city> </province>";

        }

        else if ("jiangsu".equals(sheng))

        {

            info = "<province><city>南京</city> <city>苏州</city> <city>镇江</city> </province>";

        }

        

        out.println(info);

        

        this.writeLog(sheng);

        System.out.println("" + sheng);

 

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

 

    // 写入日志

    public void writeLog(String content) {

        FileOutputStream fop = null;

        File file;

 

        try {

 

            //D:\JAVACODE2017\AjaxProject\src\com\web\servlet

            //file = new File("/src/com/web/servlet/log.txt");

            String path = "D://JAVACODE2017//AjaxProject//src//com//web//servlet/log.txt";

            file = new File(path);

            fop = new FileOutputStream(file);

            

            // if file doesnt exists, then create it

            if (!file.exists()) {

                file.createNewFile();

            }

 

            // get the content in bytes

            byte[] contentInBytes = content.getBytes();

 

            fop.write(contentInBytes);

            fop.flush();

            fop.close();

 

            System.out.println("文件内容写入成功!");

 

        } catch (IOException e) {

            e.printStackTrace();

            System.out.println("日志文件写入异常!");

        } finally {

            try {

                if (fop != null) {

                    fop.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

 

    }

 

}

 

黄金价格波动图

 

glodPrice.php界面

<html>

    <head>

        <meta http-equiv="content-type" content="text/html;charset=utf-8"/>

        <link href="Untitled-1.css" rel="stylesheet" type="text/css" />

        <script src="my.js" type="text/javascript"></script>

        <script type="text/javascript">

          

      

            var myXmlHttpRequest;

 

            function updateGoldPrice(){

                

                

                myXmlHttpRequest=getXmlHttpObject();

 

                if(myXmlHttpRequest){

                  

                    

                    //创建ajax引擎成功

                    var url="glodPriceProcess.php";

                    var data="city[]=dj&city[]=tw&city[]=ld";

 

                    myXmlHttpRequest.open("post",url,true);

 

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

 

                    myXmlHttpRequest.onreadystatechange=function chuli(){

                        

                        //接收数据json

                        if(myXmlHttpRequest.readyState==4){

                            if(myXmlHttpRequest.status==200){

                            

                                //取出并转成对象数组

                        var res_objects=eval("("+myXmlHttpRequest.responseText+")");

 

                                $('dj').innerText=res_objects[0].price;

                                $('tw').innerText=res_objects[1].price;

                                $('ld').innerText=res_objects[2].price;

 

                            }

                        }    

 

                    }

                    myXmlHttpRequest.send(data);

 

 

                    

 

                }

 

            }

 

            //使用定时器 每隔5

            window.setInterval("updateGoldPrice()",5000);

          

            

        </script>

    </head>

    <center>

        <h1>每隔5秒中更新数据(1000为基数计算涨跌)</h1>

    <table border=0 class="abc">

        <tr><td colspan="3"><img src="gjhj_bj_tit.gif" /></td></tr>

        <tr ><td>市场</td><td>最新价格$</td><td>涨跌</td></tr>

        <tr><td>伦敦</td><td id="ld">788.7</td><td><img src="down.gif" />211.3</td></tr>

        <tr><td>台湾</td><td id="tw">854.0</td><td><img src="down.gif" />146.0</td></tr>

        <tr><td>东京</td><td id="dj">1791.3</td><td><img src="up.gif" />791.3</td></tr>

    </table>

</center>

</html>

 

glodPriceProcess.php

 

<?php

 

    

    //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

    header("Content-Type: text/html;charset=utf-8");

    //告诉浏览器不要缓存数据

    header("Cache-Control: no-cache");

 

    //接收

 

    $cities=$_POST['city'];

 

    //随机的生成 三个 500-2000间数

    //$res='[{"price":"400"},{"price":"1000"},{"price":"1200"}]';

    

    $res='[';

 

 

    for($i=0;$i<count($cities);$i++){

        

        if($i==count($cities)-1){

            $res.='{"cityname":"'.$cities[$i].'" ,"price":"'.rand(500,1500).'"}]';

        }else{

            

            $res.='{"cityname":"'.$cities[$i].'" ,"price":"'.rand(500,1500).'"},';

        }

 

    }

 

    file_put_contents("d:/mylog.log",$res."\r\n",FILE_APPEND);

 

    echo $res;

 

 

?>

 

晚上的练习

 

  1. 把省市联动 和数据库
  2. 把黄金价格波动的 上下箭头指示做出来
  3. 把用户管理系统(信息共享系统),使用更加规范的mvc模式开发(引入smarty)

goods.js

var myXmlHttpRequest = "";

function updateGoldprice() {

 

    myXmlHttpRequest = getXmlHttpRequest();

    if (myXmlHttpRequest != null) {

        // window.alert("ok");

        // 向服务器发送请求

        var url = "/AjaxProject/GoldChuLiServlet";

        var deleteNum = [];// 定义要传递的数组

        deleteNum.push("dj");

        deleteNum.push("tw");

        deleteNum.push("ld");// 向数组中添加元素

        // 注意这里可以通过city[]简化传值步骤

        // var data = "city[]=dj&city[]=tw&city[]=ld";

        var data = "city=" + deleteNum;

        // window.alert(data);

        // window.alert(""+data);

        myXmlHttpRequest.open("post", url, true);

        myXmlHttpRequest.setRequestHeader("Content-Type",

                "application/x-www-form-urlencoded");

 

        // 指定回调函数

        myXmlHttpRequest.onreadystatechange = chuli;

        // 发送请求

        myXmlHttpRequest.send(data);

    }

}

 

// 开始处理业务逻辑

function chuli() {

    // 接收数据

    if (myXmlHttpRequest.readyState == 4 && myXmlHttpRequest.status == 200) {

        // 取出数据, 进行处理

        // window.alert("ok not null");

        // window

        // 转换成一个对象

        var res_obj = eval("(" + myXmlHttpRequest.responseText + ")");

 

        // 在这里同时计算一下股票的涨跌

 

        // 获取原来的的数据

        var djNow = $("dj").innerText;

        var twNow = $("tw").innerText;

        var ldNow = $("ld").innerText;

 

        // 获取当前的数据

        var djNew = res_obj[0].price;

        var twNew = res_obj[1].price;

        var ldNew = res_obj[2].price;

 

        // window.alert(djNow + " " + djNew);

        // window.alert(twNow + " " + twNew);

        // window.alert(ldNow + " " + ldNew);

 

        $("djzf").innerText = ((djNew - djNow) / djNew) * 100 + "%";

        $("twzf").innerText = ((twNew - twNow) / twNew) * 100 + "%";

        $("ldzf").innerText = ((ldNew - ldNow) / ldNew) * 100 + "%";

        //$("img1").setAttribute("src","images/down.jpg");

        //var img=document.getElementById("demo");

        //var aa = $("img1");

        window.alert(img.src);

          

        

        /*

        var tables = document.getElementsByTagName("table");

        // var trs = tables[0].getElementsByTagName("tr");

        var trs = tables[0].getElementsByTagName("tr");

        var tds = trs[2].getElementsByTagName("td");

        var img = tds[2].getElementsByTagName("img");

        //window.alert(img.length);

        //window.alert(img[0].getAttribute("src"));

        for (var i = 0; i < tds.length; i++) {

            //

            //window.alert(tds[i].innerText);

            window.alert(tds[i].getElementsByTagName("img").getAttribute("src"));

        }

        */

        //window.alert(trs2.length);

        if (djNew > djNow) {

 

        } else {

 

        }

        if (twNew > twNow) {

 

        } else {

 

        }

        if (ldNew > ldNow) {

 

        } else {

 

        }

 

        $("dj").innerText = res_obj[0].price;

        $("tw").innerText = res_obj[1].price;

        $("ld").innerText = res_obj[2].price;

        // window.alert(value);

    }

 

}

 

// 使用定时器, 5s一次

window.setInterval("updateGoldprice()", 5000);

 

 

 

goodsprice.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'goldprice.jsp' starting page</title>

 

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

<script type="text/javascript" charset="utf-8" src="js/gold.js"></script>

<script type="text/javascript" charset="utf-8" src="js/ajaxutils.js"></script>

</head>

 

<body>

    <center>

        <h1>每隔5秒中更新数据(1000为基数计算涨跌)</h1>

        <table border=1 class="abc" bordercolor="red">

            <tr>

                <td colspan="3"></td>

            </tr>

            <tr>

                <td>市场</td>

                <td>最新价格$</td>

                <td>涨跌</td>

            </tr>

            <tr>

                <td>伦敦</td>

                <td id="ld">788.7</td>

                <td id="ldzf"><img id="demo" src="images/down.jpg" />211.3</td>

            </tr>

            <tr>

                <td>台湾</td>

                <td id="tw">854.0</td>

                <td id="twzf"><img id="img2" src="images/down.jpg" />146.0</td>

            </tr>

            <tr>

                <td>东京</td>

                <td id="dj">1791.3</td>

                <td id="djzf"><img id="img3" src="images/up.jpg" />791.3</td>

            </tr>

        </table>

    </center>

 

</body>

</html>

 

 

AjaxUtils.js

//创建Ajax引擎

function getXmlHttpRequest() {

    var xmlHttpRequest;

    // 不同的浏览器获取XmlHttpRequest的方法是不一样的

    if (window.ActiveXObject) {

        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        // window.alert("ie");

    } else {

        xmlHttpRequest = new XMLHttpRequest();

        // window.alert("huohu");

    }

    return xmlHttpRequest;

}

 

function $(id) {

    return document.getElementById(id);

}

 

 

 

如果我们的代码比较复杂,可以通过

file_put_contents来输出信息到某个日志文件.(!!!!!!!)(php)

ajax实现聊天室的功能

 

需求如下:

 

 

 

 

分析实现的思路,如图所示:

  1. 创建数据库

create database chat;

create table messages(

id int unsigned primary key auto_increment,

sender varchar(64) not null,

getter varchar(64) not null,

content varchar(3600) not null,

sendTime datetime default now() not null,

isGet tinyint default 0)

 

  1. 界面

 

 

 

 

添加如下功能:

1. 增加用户表(通过id登录,并且对身份验证)

2. 防止同一个用户,多次登录.?->session和数据库

3. 公共聊天室.

4. 界面做成(框架->div+css)

5. 数据库的信息,怎么清理(后台管理),发布广告,用户的管理(后台管理程序)

 

Login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'index.jsp' starting page</title>

 

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

<script type="text/javascript" src="js/user.js" charset="utf-8"></script>

</head>

 

<body onload="chageWindowSize()">

    <center>

        <h2>欢迎登录飞Q聊天室</h2>

        <form action="/AjaxQQ2018/LoginChuLiServlet" method="post">

            用户名:<input type="text" name="username" /><br />

            密码:<input    type="password" name="password" /><br />

                <input type="submit" value="开始登录"/>

                <input type="reset" value="重新输入"/>

        </form>

    </center>

</body>

</html>

 

FriendList.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'friendlist.jsp' starting page</title>

 

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

<script type="text/javascript" src="js/user.js"></script>

<script type="text/javascript" src="js/ajaxutils.js"></script>

</head>

 

<body onload="chageWindowSize()">

    <h2>好友列表</h2>

    <ul>

 

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan">张三</li>

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan">李四</li>

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan">王五</li>

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan">刘能</li>

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan">10010</li>

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan">10011</li>

 

        <%

            for (int i = 10000; i < 10100; i++) {

        %>

        <li onmouseover="change1('over', this)" onclick="openChatRoom(this)"

            onmouseout="change1('out', this)" id="zhangsan"><%=i%></li>

        <%

            }

        %>

 

    </ul>

 

</body>

</html>

 

chatroom.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'chatroom.jsp' starting page</title>

 

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

<script type="text/javascript" src="js/ajaxutils.js" charset="utf-8"></script>

<script type="text/javascript" src="js/user.js" charset="utf-8"></script>

</head>

 

<body>

    <center>

        <h2>

            Q聊天室(用户<font color="blue" face="consolas"><span id="sender"><%=session.getAttribute("username")%></span></font>正在和好友<font

                color=red face="华文新魏"><span id="getter"><%=request.getAttribute("name")%></span></font>聊天)

        </h2>

        <textarea rows="20" cols="40" id="cons" style="font-family: '华文新魏'; font-size: 20px;"></textarea>

        <br> <input type="text" id="content" size=40 /><input

            type="button" value="发送信息" onclick="sendMessage()" />

    </center>

</body>

</html>

 

LoginChuLiservlet.java

package com.ajax.controller;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

public class LoginChuLiServlet extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html; charset=utf-8");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");

        String newName = new String(username.getBytes("iso-8859-1"), "utf-8");

        String password = request.getParameter("password");

      

        if ("123456".equals(password))

        {

            

            HttpSession session = request.getSession();

            session.setAttribute("username", newName);

            session.setMaxInactiveInterval(1000*60*5);

            request.getRequestDispatcher("/WEB-INF/user/friendlist.jsp").forward(request, response);

        }

        else

        {

            request.getRequestDispatcher("/WEB-INF/user/login.jsp").forward(request, response);

        }

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

 

}

 

SendMessageServlet.java

package com.ajax.controller;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.ajax.service.MessageService;

 

public class SendMessageServlet extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html; charset=utf-8");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        // 用于处理发送信息

        // 1.接受信息

        // [注意window.open()会以get方式提交数据, Ajax默认是以post方式提交数据]

        String sender = (String) request.getSession().getAttribute("username");

        String getter = request.getParameter("getter");

        String newGetter = new String(getter.getBytes("iso-8859-1"), "utf-8");

        String content = request.getParameter("con");

        String newContent = new String(content.getBytes("iso-8859-1"), "utf-8");

 

        System.out.println("sender: " + sender + " getter: " + newGetter

                + " content: " + newContent);

 

        // 开始添加

        MessageService mService = new MessageService();

        if (mService.addMessage(sender, newGetter, newContent)) {

            System.out.println("本条消息记录数据添加成功!!!");

            // XML数据格式返回

            // out.println("<mes><sender></getter></mes>");

            out.println(newContent + " (本条消息记录数据发送成功!!!)");

        }

 

        // 去出去了就把数据库设置为已经取出

        //mService.setGetZero(sender, getter);

 

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

 

}

 

GetMessageServlet.java

package com.ajax.controller;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.jms.Message;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.ajax.service.MessageService;

 

public class GetMessageServlet extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/xml; charset=utf-8");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        String sender = (String) request.getSession().getAttribute("username");

        String getter = request.getParameter("sender");

        // .getBytes("iso-8859-1"), "utf-8"

        String newSender = "";

        if (sender != null) {

            newSender = new String(sender.getBytes("iso-8859-1"),

                    "utf-8");

        }

 

        System.out.println("接收数据人: 接受者" + getter + " 发送者: " + sender);

 

        // 取出数据

        MessageService mService = new MessageService();

        String messageInfo = mService.getMessage(newSender, getter);

        response.setDateHeader("Expires", -1);

        // 把信息返回出去

        out.println(messageInfo);

        

        //信息如果发出去就置为0

        //mService.setGetZero(newSender, getter);

        

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

 

}

 

GoChatRoomServlet.java

package com.ajax.controller;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class GoChatRoomServlet extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/html; charset=utf-8");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");

        String newName = new String(name.getBytes("iso-8859-1"), "utf-8");

        System.out.println(""+name+" "+"1"+newName+"1");

        request.setAttribute("name", newName);

        request.getRequestDispatcher("/WEB-INF/user/chatroom.jsp").forward(request, response);

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

 

}

 

Man ageService.java

package com.ajax.service;

 

import com.ajax.dao.SqlHelper;

 

import java.sql.*;

 

public class MessageService {

 

    // 定义一个全局变量, 用于及时返回用户聊天信息

    private static String message = "";

 

    public boolean addMessage(String sender, String getter, String content) {

        boolean b = true;

        System.out.println("insert.getParameter:" + sender + " " + getter + " "

                + content);

        String sql = "insert into messages (sender, getter, content) values ('"

                + sender + "', '" + getter + "', '" + content + "')";

        try {

            SqlHelper.executeUpdate(sql, null);

        } catch (Exception e) {

            b = false;

            // TODO: handle exception

            e.printStackTrace();

 

        }

        return b;

    }

 

    // 取出数据, 把数据组织好返回给客户端

    public String getMessage(String sender, String getter) {

 

        // 进来的时候把信息清空

        message = "";

 

        System.out.println("SQL: sender" + sender + " getter: " + getter);

        String sql = "select * from messages where (getter = '" + sender

                + "' and sender='" + getter + "') and isGet=0";

        ResultSet rs = SqlHelper.executeQuery(sql, null);

        System.out.println("select sql: " + sql);

        // xml格式

        // String messageInfo =

        // "<mess><messid>1</messid><sender>001</sender><getter>002</getter><con>hello</con><time>20170201</time></mess>";

        String messageInfo = "<mess>";

        try {

            while (rs.next()) {

                System.out.println("rs.next info:");

                String messid = rs.getObject(1).toString();

                String con = rs.getObject(4).toString();

                String time = rs.getObject(5).toString();

                System.out.println(messid + " " + con + " " + time);

                messageInfo += "<messid>" + messid + "</messid><sender>"

                        + sender + "</sender><getter>" + getter

                        + "</getter><con>" + con + "</con><time>" + time

                        + "</time>";

            }

            messageInfo += "</mess>";

            System.out.println("messageInfo: " + messageInfo);

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } finally {

            SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getCt());

        }

 

        // 把信息返回出去

        message = messageInfo;

        //如果message中没有信息, 说明isGet=1

        //如果message中有信息,说明isGet=0

        System.out.println("message is: "+message);

        //<mess></mess>

        if (message.equals("<mess></mess>") || message.equals("")){

            //isGet=1

            System.out.println("-----------------------------我没有拿到数据");

        }

        else{

            //信息走到这里说明信息我已经拿到手了,(不用管其他的)

            System.out.println("-----------------------------我已经查到数据");

            //this.setGetZero(sender, getter);

            // 取完之后设置为1

            

            //[特别重要: 注意这里的SQL更新语句的sendergetter是给接受者看的, 与上面的SQL语句刚好相反]

             sql = "update messages set isGet = 1 where sender = '" + getter

                    + "' and getter='" + sender + "'"; //ok

             //sql = "update messages set isGet = 1 where sender = '" + getter

                        //+ "' and getter='" + sender + "'"; //error

            System.out.println("update sql: " + sql);

            SqlHelper.executeUpdate(sql, null);

        }

        return messageInfo;(上面的修改操作并不会影响到这里已经拿到的messageInfo

    }

 

}

 

user.js

function change1(val, obj) {

    if (val == 'over') {

        obj.style.color = "red";

        obj.style.cursor = "hand";

    } else if (val == 'out') {

        obj.style.color = "black";

    }

}

 

function chageWindowSize() {

    // window.alert("12");

    window.resizeTo(400, 700);

    window.moveTo(400, 190);

}

 

var getterName = "";

function openChatRoom(obj) {

    // window.alert("open new window");

    // 默认是get方式提交, encodeURI(obj.innerText)是使用URI编码

    window.open("/AjaxQQ2018/GoChatRoomServlet?name="

            + encodeURI(obj.innerText) + "", "_blank");

    getterName = obj.innerText;

    // window.alert(getterName);

}

 

 

var mXmlHttpRequest = "";

 

// 接受信息者(只要这个函数上线了, 就说明信息接收了)

function getMessage() {

    mXmlHttpRequest = getXmlHttpRequest();

    if (mXmlHttpRequest != null) {

 

        var url = "/AjaxQQ2018/GetMessageServlet";

        var data = "sender=" + $("getter").innerText;

        // window.alert($("getter").innerText+" "+data);

        mXmlHttpRequest.open("post", url, true);

        mXmlHttpRequest.setRequestHeader("Content-Type",

                "application/x-www-form-urlencoded");

        // 指定处理结果的函数

        mXmlHttpRequest.onreadystatechange = function chuli() {

            if (mXmlHttpRequest.readyState == 4

                    && mXmlHttpRequest.status == 200) {

                // 得到返回信息

                var message = mXmlHttpRequest.responseXML;

 

                // window.alert(message);

                //<mess><messid>71</messid><sender>10011</sender><getter>10010</getter><con>nihoa</con><time>2017-07-31 10:00:24.0</time><messid>72</messid><sender>10011</sender><getter>10010</getter><con>12121212</con><time>2017-07-31 10:01:11.0</time><messid>73</messid><sender>10011</sender><getter>10010</getter><con>12121212</con><time>2017-07-31 10:01:23.0</time><messid>74</messid><sender>10011</sender><getter>10010</getter><con>haha</con><time>2017-07-31 10:04:15.0</time><messid>75</messid><sender>10011</sender><getter>10010</getter><con>121212</con><time>2017-07-31 10:05:06.0</time></mess>

                var cons = message.getElementsByTagName("con");

                var time = message.getElementsByTagName("time");

                // window.alert(cons+" "+time);

                 //window.alert(cons.length+" "+time.length);

                if (cons.length != 0) {

                    for (var i = 0; i < cons.length; i++) {

                        var getter = $("getter").innerText;

                        var sender =$("sender").innerText;

                        //window.alert(getter+" "+sender);

                        // window.alert("get: "+getter+" sen:"+sender);

                        // xx yy

                        

                        //注意在JavaScript中不能出现String, int 等数据类型, 所有的数据都用var表示

                        //生成时间:new Date().toLocaleString()

                        $("cons").style.color = "blue";

                        var con = time[i].childNodes[0].nodeValue+" "+getter+" said to "+sender+" :"+ cons[i].childNodes[0].nodeValue;

                        //利用"\r\n接收一条数据就换行显示"

                        $("cons").value += con+"\r\n";

                        //window.alert(con);

                        //$("content").innerText = "";

                    }

                }

 

            }

        };

        // window.alert(data);

        // window.alert(url);

        mXmlHttpRequest.send(data);

    }

}

// 开始不断读取数据

// 使用定时器, 5s一次

window.setInterval("getMessage()", 5000);

 

// 发送信息者

function sendMessage() {

    // 发送信息

    mXmlHttpRequest = getXmlHttpRequest();

    if (mXmlHttpRequest != null) {

        var url = "/AjaxQQ2018/SendMessageServlet";

        var data = "con=" + $("content").value + "&getter="

                + $("getter").innerText;

        // window.alert(url+" "+data);

 

        mXmlHttpRequest.open("post", url, true);

        mXmlHttpRequest.setRequestHeader("Content-Type",

                "application/x-www-form-urlencoded");

 

        // 指定回调函数

        mXmlHttpRequest.onreadystatechange = function chuli() {

            if (mXmlHttpRequest.readyState == 4

                    && mXmlHttpRequest.status == 200) {

                // 得到返回信息

                var con = mXmlHttpRequest.responseText;

                //window.alert(con);

                $("cons").style.color="red";

                $("cons").value = new Date().toLocaleString()+" You have said to "+$("getter").innerText+" :"+con;

                $("content").innerText = "";

                

                

            }

        };

        // 正式发送请求

        mXmlHttpRequest.send(data);

    }

 

}

 

 

 

相关文章
|
7月前
|
XML 前端开发 JavaScript
AJAX 前端开发利器:实现网页动态更新的核心技术
**AJAX** 允许网页在不刷新的情况下更新内容,实现异步与服务器交换数据。通过JavaScript的XMLHttpRequest对象,可发送和接收数据。当用户触发事件(如点击),函数向服务器发送GET请求,服务器响应后更新指定HTML部分。AJAX并非编程语言,而是利用浏览器内置对象、JavaScript和DOM技术。核心是XMLHttpRequest对象,它有多种方法(如`open()`和`send()`)和属性(如`onreadystatechange`、`readyState`和`status`)来处理请求和响应。
123 2
AJAX 前端开发利器:实现网页动态更新的核心技术
|
7月前
|
设计模式 前端开发 JavaScript
Ajax技术【Ajax 实战】(二)-全面详解(学习总结---从入门到深化)
Ajax技术【Ajax 实战】(二)-全面详解(学习总结---从入门到深化)
60 0
|
7月前
|
XML JSON 前端开发
JavaWeb----Ajax技术
JavaWeb----Ajax技术
83 0
|
7月前
|
JSON 前端开发 JavaScript
AJAX 课程学习笔记三
AJAX 课程学习笔记三
|
21天前
|
XML 前端开发 JavaScript
PHP与Ajax在Web开发中的交互技术。PHP作为服务器端脚本语言,处理数据和业务逻辑
本文深入探讨了PHP与Ajax在Web开发中的交互技术。PHP作为服务器端脚本语言,处理数据和业务逻辑;Ajax则通过异步请求实现页面无刷新更新。文中详细介绍了两者的工作原理、数据传输格式选择、具体实现方法及实际应用案例,如实时数据更新、表单验证与提交、动态加载内容等。同时,针对跨域问题、数据安全与性能优化提出了建议。总结指出,PHP与Ajax的结合能显著提升Web应用的效率和用户体验。
36 3
|
1月前
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
在Web开发中,前后端的高效交互是提升用户体验的关键。本文通过一个基于Flask框架的博客系统实战案例,详细介绍了如何使用AJAX和Fetch API实现不刷新页面查看评论的功能。从后端路由设置到前端请求处理,全面展示了这两种技术的应用技巧,帮助Python Web开发者提升项目质量和开发效率。
44 1
|
1月前
|
JSON 前端开发 JavaScript
java-ajax技术详解!!!
本文介绍了Ajax技术及其工作原理,包括其核心XMLHttpRequest对象的属性和方法。Ajax通过异步通信技术,实现在不重新加载整个页面的情况下更新部分网页内容。文章还详细描述了使用原生JavaScript实现Ajax的基本步骤,以及利用jQuery简化Ajax操作的方法。最后,介绍了JSON作为轻量级数据交换格式在Ajax应用中的使用,包括Java中JSON与对象的相互转换。
43 1
|
3月前
|
前端开发
React技术栈-react使用的Ajax请求库实战案例
这篇文章介绍了在React应用中使用Axios和Fetch库进行Ajax请求的实战案例,展示了如何通过这些库发送GET和POST请求,并处理响应和错误。
61 10
React技术栈-react使用的Ajax请求库实战案例
|
4月前
|
前端开发 Java UED
告别页面刷新时代:Struts 2 Ajax技术揭秘,轻松实现动态加载,Web应用焕然一新!
【8月更文挑战第31天】在Web应用开发中,用户体验至关重要。为减少页面刷新带来的不适,Ajax技术应运而生。Struts 2作为流行的Java EE框架,通过内置的Ajax支持简化了无刷新页面动态加载的实现。本文通过对比传统请求响应模式,展示了Struts 2如何轻松实现Ajax功能,提升了用户体验和开发效率,并灵活地实现了数据交换。然而,使用Ajax时还需注意SEO和跨域请求等局限性。
44 0
|
5月前
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
【7月更文挑战第13天】在Web开发中,AJAX和Fetch API是实现页面无刷新数据交换的关键。在Flask博客系统中,通过创建获取评论的GET路由,我们可以展示使用AJAX和Fetch API的前端实现。AJAX通过XMLHttpRequest发送请求,处理响应并在成功时更新DOM。Fetch API则使用Promise简化异步操作,代码更现代。这两个工具都能实现不刷新页面查看评论,Fetch API的语法更简洁,错误处理更直观。掌握这些技巧能提升Python Web项目的用户体验和开发效率。
67 7