zoukankan      html  css  js  c++  java
  • 第88节:Java中的Ajax和ASP.NET和TCP/IP 教程和JSON

    标题图

    第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 点赞
  • 相关阅读:
    核心API的使用(给定一个字符串,统计每个字符出现的次数)
    将博客搬至CSDN
    [DEBUG] python写文件时print漏掉整行数据
    [DEBUG] pyinstaller打包-命令行报错 pyinstaller failed to execute script 脚本名
    [DEBUG] springboot结合freemaker和js实现页面跳转和传值-踩坑记录
    724. 寻找数组的中心索引
    1010. 总持续时间可被 60 整除的歌曲
    27.移除元素
    [tensorflow] 入门day1-数据整理与展示
    [tensorflow] 安装
  • 原文地址:https://www.cnblogs.com/dashucoding/p/11140326.html
Copyright © 2011-2022 走看看