第88節:Java中的Ajax和ASP.NET和TCP/IP 教程和JSON

達叔小生發表於2019-02-26

標題圖

第88節:Java中的Ajax和Jquery

ajax是什麼?有什麼用?原理,怎麼用?

ajax是asynchronous javascript and xml(非同步javascript和xml),是指一種建立互動式網頁應用的網頁開發技術。

ajax

如使用者註冊,輸入的使用者名稱,提示已經被註冊了。

AJAX

Asynchronous JavaScript and XML

ajax是一種不用重新載入整個網頁的情況下,能夠更新部分網頁的技術。

什麼是ajax?

是 非同步 JavaScript 和 XML,是一種用於快速動態網頁的技術,能夠在後臺與伺服器進行少量的資料交換,就可以實現網頁的非同步更新了,就不用重新載入整個網頁,讓部分需要進行更新的內容進行更新了。

AJAX 例項

<html>
<body>
// div 來自伺服器的資訊
<div id="myDiv">
<h3>dashucoding</h3>
</div>

<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
.... AJAX  ...
}
</script>
</head>

建立 XMLHttpRequest 物件

XMLHttpRequestAJAX 的基礎
XMLHttpRequest 用於在後臺與伺服器交換資料
IE5 和 IE6 使用 ActiveXObject

建立物件:

variable=new XMLHttpRequest();
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  { // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

XMLHttpRequest 物件用於和伺服器交換資料

xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();

open(method,url,async)
method GET 或 POST 請求的型別
url 
async true(非同步)或 false(同步)

send(string) 將請求傳送到伺服器
僅用於 POST 請求

GET 和 POST:

GET更快更簡單。使用POST的情況:

  1. 無法使用緩衝檔案
  2. 向伺服器傳送大量資料
  3. 傳送未知字元

GET 請求

xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();

效果

xmlhttp.open("GET","demo_get2.asp?fname=dashu&lname=coding",true);
xmlhttp.send();

POST 請求

xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=dashu&lname=Coding");

// setRequestHeader(header,value)
header: 規定頭的名稱 
value: 規定頭的值 

url – 伺服器上的檔案

xmlhttp.open("GET","ajax_test.asp",true);
// 可以是任何型別的檔案

True 或 False

非同步 JavaScript 和 XML

xmlhttp.open("GET","ajax_test.asp",true);
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();

非同步false

xmlhttp.open("GET","test1.txt",false);
// 不推薦使用

xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

伺服器響應

屬性 描述
responseText 獲取字串式的響應資料
responseXML 獲取xml式的響應資料

responseText屬性:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;

onreadystatechange 事件

readyState 被改變時,會觸發 onreadystatechange事件,readyState屬性存有XMLHttpRequest的資訊。

onreadystatechange 儲存函式
readyState
0: 請求未初始化 
1: 伺服器連線已建立 
2: 請求已接收 
3: 請求處理中 
4: 請求已完成,且響應已就緒 
status
200: "OK"
404: 未找到頁面
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}

ASP.NET

ASP.NET 是一個開發框架

開發模式

描述

效果

TCP/IP 教程

描述

描述

描述

XmlHttp

abort取消當前請求,語法:

oXMLHttpRequest.abort();

getAllResponseHeaders
獲取響應的所有http頭

語法:

strValue = oXMLHttpRequest.getAllResponseHeaders();
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
xmlhttp.open("GET", "http://localhost/sample.xml", false);
xmlhttp.send();
alert(xmlhttp.getAllResponseHeaders());

getResponseHeader:
從響應資訊中獲取指定的http頭

語法:

strValue = oXMLHttpRequest.getResponseHeader(bstrHeader);
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
xmlhttp.open("GET", "http://localhost/sample.xml", false);
xmlhttp.send();
alert(xmlhttp.getResponseHeader("Server"));

onreadystatechange
指定當readyState屬性改變時的事件處理控制程式碼

語法:

oXMLHttpRequest.onreadystatechange = funcMyHandler;

描述

介紹 JSON

一種輕量級的資料交換格式

結構

一個物件以“{” 開始,“}” 結束

每個“名稱”後跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔

陣列是值的有序集合

以“[”開始,“]”結束,值之間使用“,”分隔

Ajax

獲取文字內容
document.getElementById("username").value
通過XmlHttpRequest請求,XML+http+Request

請求

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

    function  ajaxFunction(){
       var xmlHttp;
       try{ 
            xmlHttp=new XMLHttpRequest();
        }
        catch (e){
           try{
                 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
              }
            catch (e){
              try{
                 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
              catch (e){}
              }
        }

        return xmlHttp;
     }

    //執行get請求
    function get() {
        
        //1. 建立xmlhttprequest 物件
        var request = ajaxFunction();
        
        //2. 傳送請求。

//      request.open("GET" ,"/DemoServlet01" ,true );
        request.open("GET" ,"/DemoServlet01?name=dashu&age=18" ,true );
        request.send();
    }
    
    //執行get請求
    function get() {
        
        //建立xmlhttprequest 物件
        var request = ajaxFunction();
        
        //傳送請求
        request.open("GET" ,"/DemoServlet01?name=dashu&age=18" ,true );
        
        //獲取響應資料  
        request.onreadystatechange = function(){
            
            if(request.readyState == 4 && request.status == 200){
                //彈出響應的資訊
                alert(request.responseText);
            }
        }
        request.send();
    }

</script>

</head>
<body>

    <h3><a href="" onclick="get()">使用Ajax方式傳送Get請求</a></h3>

</body>
</html>

程式碼

Post

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

    //建立物件
    function  ajaxFunction(){
       var xmlHttp;
       try{ 
            xmlHttp=new XMLHttpRequest();
        }
        catch (e){
           try{
                 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
              }
            catch (e){
              try{
                 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
              catch (e){}
              }
        }

        return xmlHttp;
     }
    
    function post() {
        //建立物件
        var request = ajaxFunction();
        
        //傳送請求
        request.open( "POST", "/DemoServlet01", true );
        
        //獲取伺服器傳送過來的資料
        request.onreadystatechange=function(){
            if(request.readyState==4 && request.status == 200){
                alert("post:"+request.responseText);
            }
        }

        request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        
        //帶資料過去  , 在send方法裡面寫表單資料。 
        request.send("name=dashucoding&age=19");
    }
    
    
</script>

</head>
<body>
    <h3>
        <a href="" onclick="post()">使用Ajax方式傳送Post請求</a>
    </h3>
</body>
</html>

結構

資料請求,建立物件:

效果

校驗使用者名稱

建立物件

jar

c3p0

dao

import java.sql.SQLException;
public interface UserDao {
    /**
     * 用於檢測使用者名稱是否存在
     */
    boolean checkUserName(String username) throws SQLException;
}

util:
結構

public class JDBCUtil02 {
    
    static ComboPooledDataSource dataSource = null;
    static{
        dataSource = new ComboPooledDataSource();
    }
    
    public static DataSource getDataSource(){
        return dataSource;
    }
    
    /**
     * 獲取連線物件
     * @return
     * @throws SQLException 
     */
    public static Connection getConn() throws SQLException{
        return dataSource.getConnection();
    }
    
    /**
     * 釋放資源
     * @param conn
     * @param st
     * @param rs
     */
    public static void release(Connection conn , Statement st , ResultSet rs){
        closeRs(rs);
        closeSt(st);
        closeConn(conn);
    }
    public static void release(Connection conn , Statement st){
        closeSt(st);
        closeConn(conn);
    }

    
    private static void closeRs(ResultSet rs){
        try {
            if(rs != null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            rs = null;
        }
    }
    
    private static void closeSt(Statement st){
        try {
            if(st != null){
                st.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            st = null;
        }
    }
    
    private static void closeConn(Connection conn){
        try {
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            conn = null;
        }
    }
}
public class TextUtils {

    /**
     * 判斷某一個字串是否為空。
     */
    public static boolean isEmpty(CharSequence s){
        return s==null || s.length() == 0;
    }
}

servlet

try{
 request.setCharacterEncoding("UTF-8");
 String name = request.getParameter("name");
 UserDao dao = new UserDaoImpl();
 boolean isExist = dao.checkUserName(name);
 
 if(isExist){
  response.getWriter().println(1);// 存在
 }else{
  response.getWriter().println(2); // 反之
 }
}catch(SQLException e){
 e.printStackTrace();
}
xxx.jsp
<input type="text" name="name" id="name"  onblur="checkUserName()"><span id="span01"></span>

效果

<script type="text/javascript">
    function checkUserName() {
        //獲取輸入框的值
        var name = document.getElementById("name").value; 
        //建立物件
        var request = ajaxFunction();
        
        //傳送請求
        request.open("POST"  ,"/CheckUserNameServlet" , true );
        
        //註冊狀態,獲取伺服器傳過來的資料
        request.onreadystatechange = function(){
            if(request.readyState == 4 && request.status == 200){
                var data = request.responseText;
                if(data == 1){
                    document.getElementById("span01").innerHTML = "<font color=`red`>使用者名稱已存在!</font>";
                }else{
                    document.getElementById("span01").innerHTML = "<font color=`green`>使用者名稱可用!</font>";
                }
            }
            
        }
        
        request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        // 輸入框傳送name
        request.send("name="+name);
    }
    
</script>

結言

好了,歡迎在留言區留言,與大家分享你的經驗和心得。

感謝你學習今天的內容,如果你覺得這篇文章對你有幫助的話,也歡迎把它分享給更多的朋友,感謝。

達叔小生:往後餘生,唯獨有你
You and me, we are family !
90後帥氣小夥,良好的開發習慣;獨立思考的能力;主動並且善於溝通
簡書部落格: 達叔小生
https://www.jianshu.com/u/c785ece603d1

結語

  • 下面我將繼續對 其他知識 深入講解 ,有興趣可以繼續關注
  • 小禮物走一走 or 點贊

相關文章