Ajax技術實戰操練課堂學習筆記

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 的運行原理分析

 

 

 

看一個需求: javascript

 

  • ajax在什麼地方用的多

 

1 動態加載數據,按需取得數據。【樹形菜單、聯動菜單.../省市聯動】 php

2 改善用戶體驗。【輸入內容前提示、帶進度條文件上傳... css

 

3 電子商務應用。    【購物車、郵件訂閱... html

4 訪問第三方服務。    【訪問搜索服務、rss閱讀器】 java

5. 數據的佈局刷新 node

 

  • 經典的案例

 

使用ajax與服務器通訊的的步驟 web

  1. 建立一個XMLHttpRequest對象
  2. 建立url, data,經過 xmlHttpRequest.send()
  3. 服務器端接收 ajax的請求,作相應處理(操做數據庫),而後返回結果(echo 語句)
  4. 客戶端經過xmlHttpRequest的屬性 reponseText , responseXML 取的數據,而後就完成局部刷新當前頁面任務

 

使用 ajax完成用戶名的驗證(get方式提交數據)

 

register.php ajax

 

<html> sql

<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);

    }

 

}

相關文章
相關標籤/搜索