标签:定位器 目录结构 info encode 拼接 发送请求 存储 原理 json
目录结构:
Ajax是Asynchronous JavaScript and XML(异步的JavaScript和XML)的简介,Ajax并不是一门新的编程语言,而是一种使用现有标准的新方法。它能够在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
通过这个原理图,我们可以看出我们写的javascript代码首先会经过ajax引擎,由ajax引擎负责和server进行通信,再将通信的结果返回给浏览器。这样就不需要刷新整个网页,从而实现向服务器请求数据。
所有现代的浏览器都内建了XMLHttpRequest对象,创建的语法为: var xmlhttp=new XMLHttpRequest(); 。
老版本的IE5,IE6使用ActiveX对象,语法为: var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 。
xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ //document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
readState的状态码:
status的状态码:
xmlhttp.open(Method,URL,async);
xmlhttp.send();
这里涉及到参数的问题,如果是使用POST请求提交参数,那么参数需要在send()方法中传入,如果使用GET请求提交参数,那么参数需要拼接到URL后面。
html文件:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户登录</title> <script type="text/javascript"> function userSubmit(){ //创建对象 var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //传入回调函数onreadystatechange xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){//请求成功 document.getElementById("logininfo").innerHTML=xmlhttp.responseText; } } //发送请求 xmlhttp.open("POST","login.do",true); //如果希望通过POST传输数据,那么应该先通过setRequestHeader()添加Http头数据 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); var unamevalue=document.getElementById("unameid").value; var upassvalue=document.getElementById("upassid").value; xmlhttp.send("uname="+unamevalue+"&upass="+upassvalue); } </script> </head> <body> <div> 请输入用户名:<input type="text" id="unameid" name="uname"/><p><p> 请输入密码:<input type="password" id="upassid" name="upass"/><p><p> <input type="button" value="点击我" onclick="userSubmit()"/><p><P> <span id="logininfo"></span> </div> </body> </html>
servlet文件:
package cn.user.login; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** */ @WebServlet("/login.do") public class UserLogin extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String name=request.getParameter("uname"); String password=request.getParameter("upass"); //进行数据库的查询,对比name和password //此处省略对数据库的查询,使用name=张三,password=123456; if("张三".equals(name) && "123456".equals(password)){ response.getWriter().append("登录成功"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
上面的代码如果需要使用GET请求(参数应该拼接到url上),那么将上面的文件改为,
html文件:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户登录</title> <script type="text/javascript"> function userSubmit(){ //创建对象 var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //传入回调函数onreadystatechange xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){//请求成功 document.getElementById("logininfo").innerHTML=xmlhttp.responseText; } } var unamevalue=document.getElementById("unameid").value; var upassvalue=document.getElementById("upassid").value; //发送请求 xmlhttp.open("GET","login.do?uname="+unamevalue+"&upass="+upassvalue,true); xmlhttp.send(); } </script> </head> <body> <div> 请输入用户名:<input type="text" id="unameid" name="uname"/><p><p> 请输入密码:<input type="password" id="upassid" name="upass"/><p><p> <input type="button" value="点击我" onclick="userSubmit()"/><p><P> <span id="logininfo"></span> </div> </body> </html>
servlet文件:
package cn.user.login; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** */ @WebServlet("/login.do") public class UserLogin extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); String name=new String(request.getParameter("uname").getBytes("ISO-8859-1"),"utf-8"); String password=new String(request.getParameter("upass").getBytes("ISO-8859-1"),"utf-8"); //进行数据库的查询,对比name和password //此处省略对数据库的查询,使用name=张三,password=123456; if("张三".equals(name) && "123456".equals(password)){ response.getWriter().append("登录成功"); }else{ response.getWriter().append("登录失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
上面使用原生的js代码过于繁琐,jQuery对ajax进行了封装,提供了方法,比如常用的:$.ajax(),$.get(),$.post(),$.getJSON()方法。
下面使用$.ajax()函数进行演示:
html代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax测试</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".submitButton").click(function(){ $.ajax({ url:"login.do?uname="+$(".unameclass").val()+"&upass="+$(".unamepass").val(), type:"GET", dataType:"JSON", async:"true", success:function(res){ $(".logininfo").html(res.result.logininfo); }, error:function(xhr){ alert("错误提示: " + xhr.status + " " + xhr.statusText); } }); }); }) </script> </head> <body> <div> 用户名:<input type="text" class="unameclass" /><p><p> 密码:<input type="text" class="unamepass" /><p><p> <input type="button" value="提交" class="submitButton"/><p><p> <span class="logininfo"></span> </div> </body> </html>
servlet代码:
package cn.user.login; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** */ @WebServlet("/login.do") public class UserLogin extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); String name=new String(request.getParameter("uname").getBytes("ISO-8859-1"),"utf-8"); String password=new String(request.getParameter("upass").getBytes("ISO-8859-1"),"utf-8"); //进行数据库的查询,对比name和password //此处省略对数据库的查询,使用name=张三,password=123456; int errorCode;//错误码,0表示无错误,1表示有错误 Map map1=new HashMap<>(); Map<String,String> map2=new HashMap<String,String>(); if("张三".equals(name) && "123456".equals(password)){ errorCode=0; map2.put("logininfo", "登录成功"); }else{ errorCode=1; map2.put("logininfo", "登录失败"); } map1.put("errorcode", errorCode); map1.put("result", map2); //将Map集合转化为JSON字符串 String strjson=new Gson().toJson(map1); response.getWriter().append(strjson); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
上面的servlet代码,将Map集合转化为了json字符串,首先需要导入 gson-2.3.1.jar 包,关于这种方式笔者在下面还会讲解。如果我们不采用Map集合转化为json字符串的方式,那么我们也手动拼接字符串的方法,只不过这种方法在处理数据量大的json数据时,显得力不从心。
在上面的案例中,我们也使用了ajax函数,那里是使用GET请求的方式,下面我们使用POST方式
html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax测试</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".submitButton").click(function(){ $.ajax({ url:"login.do", type:"POST", data:{"uname":$(".unameclass").val(),"upass":$(".unamepass").val()}, dataType:"JSON", async:"true", success:function(res){ $(".logininfo").html(res.result.logininfo); }, error:function(xhr){ alert("错误提示: " + xhr.status + " " + xhr.statusText); } }); }); }) </script> </head> <body> <div> 用户名:<input type="text" class="unameclass" /><p><p> 密码:<input type="text" class="unamepass" /><p><p> <input type="button" value="提交" class="submitButton"/><p><p> <span class="logininfo"></span> </div> </body> </html>
servlet页面:
package cn.user.login; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** */ @WebServlet("/login.do") public class UserLogin extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); String name=request.getParameter("uname"); String password=request.getParameter("upass"); //进行数据库的查询,对比name和password //此处省略对数据库的查询,使用name=张三,password=123456; int errorCode;//错误码,0表示无错误,1表示有错误 Map map1=new HashMap<>(); Map<String,String> map2=new HashMap<String,String>(); if("张三".equals(name) && "123456".equals(password)){ errorCode=0; map2.put("logininfo", "登录成功"); }else{ errorCode=1; map2.put("logininfo", "登录失败"); } map1.put("errorcode", errorCode); map1.put("result", map2); //将Map集合转化为JSON字符串 String strjson=new Gson().toJson(map1); response.getWriter().append(strjson); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
这个函数表明请求数据的方式为GET,请求的数据但是不需要添加到url中,该函数中专门有参数接受参数。
html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax测试</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".submitButton").click(function(){ $.get( "login.do", {"uname":$(".unameclass").val(),"upass":$(".unamepass").val()}, function(res){ $(".logininfo").html(res.result.logininfo); }, "JSON" ); }); }) </script> </head> <body> <div> 用户名:<input type="text" class="unameclass" /><p><p> 密码:<input type="text" class="unamepass" /><p><p> <input type="button" value="提交" class="submitButton"/><p><p> <span class="logininfo"></span> </div> </body> </html>
servlet页面:
package cn.user.login; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** */ @WebServlet("/login.do") public class UserLogin extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); String name=new String(request.getParameter("uname").getBytes("ISO-8859-1"),"utf-8"); String password=new String(request.getParameter("upass").getBytes("ISO-8859-1"),"utf-8"); //进行数据库的查询,对比name和password //此处省略对数据库的查询,使用name=张三,password=123456; int errorCode;//错误码,0表示无错误,1表示有错误 Map map1=new HashMap<>(); Map<String,String> map2=new HashMap<String,String>(); if("张三".equals(name) && "123456".equals(password)){ errorCode=0; map2.put("logininfo", "登录成功"); }else{ errorCode=1; map2.put("logininfo", "登录失败"); } map1.put("errorcode", errorCode); map1.put("result", map2); //将Map集合转化为JSON字符串 String strjson=new Gson().toJson(map1); response.getWriter().append(strjson); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax测试</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".submitButton").click(function(){ $.post( "login.do", {"uname":$(".unameclass").val(),"upass":$(".unamepass").val()}, function(res){ $(".logininfo").html(res.result.logininfo); }, "JSON" ); }); }) </script> </head> <body> <div> 用户名:<input type="text" class="unameclass" /><p><p> 密码:<input type="text" class="unamepass" /><p><p> <input type="button" value="提交" class="submitButton"/><p><p> <span class="logininfo"></span> </div> </body> </html>
servlet页面:
package cn.user.login; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** */ @WebServlet("/login.do") public class UserLogin extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); String name=request.getParameter("uname"); String password=request.getParameter("upass"); //进行数据库的查询,对比name和password //此处省略对数据库的查询,使用name=张三,password=123456; int errorCode;//错误码,0表示无错误,1表示有错误 Map map1=new HashMap<>(); Map<String,String> map2=new HashMap<String,String>(); if("张三".equals(name) && "123456".equals(password)){ errorCode=0; map2.put("logininfo", "登录成功"); }else{ errorCode=1; map2.put("logininfo", "登录失败"); } map1.put("errorcode", errorCode); map1.put("result", map2); //将Map集合转化为JSON字符串 String strjson=new Gson().toJson(map1); response.getWriter().append(strjson); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
这个函数就是指定$.get()函数返回数据的类型是JSON,只需要将$.get()函数案例中html页面改为:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax测试</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".submitButton").click(function(){ $.getJSON( "login.do", {"uname":$(".unameclass").val(),"upass":$(".unamepass").val()}, function(res){ $(".logininfo").html(res.result.logininfo); }, ); }); }) </script> </head> <body> <div> 用户名:<input type="text" class="unameclass" /><p><p> 密码:<input type="text" class="unamepass" /><p><p> <input type="button" value="提交" class="submitButton"/><p><p> <span class="logininfo"></span> </div> </body> </html>
因为json字符串和java中的Map集合对象非常类似,两者之间可以相互转化,不过之前我们先需要导包 gson.jar
将字符串转化为Map集合
/* * 参数1. 要转换为对象的JSON格式字符串 * 参数2. 要转换的对象的类信息 */ ClassObject = GsonInstance.fromJSON(JSON字符串,Class);
将字符串转化字符串使用函数
String str_json=GsonInstance.toJson(Map map);
下面通过java代码来看看:
package cn.gson.test; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; public class GSON_TEST { public static void main(String[] args) { Map map1=new HashMap(); Map map2=new HashMap(); map2.put("info", "测试json"); map1.put("error", "no"); map1.put("detail", map2); Gson gsoninstance=new Gson(); //将map集合转化为json字符串 String strjson=gsoninstance.toJson(map1); System.out.println(strjson);//{"detail":{"info":"测试json"},"error":"no"} Map map3=new HashMap(); map3=gsoninstance.fromJson(strjson, Map.class); System.out.println(map3);//{detail={info=测试json}, error=no} } }
java对于JSON的解析不仅仅只有这一种方式,下面查询天气的demo,我们使用另一种将json字符串转化为java中Map集合
首先我们需要导入json.jar包,
项目文件结构图片:
html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>天气查询</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".submit").click(function(){ $.ajax({ url:"weather.do", data:{"cityname":$(".city").val()}, dataType:"JSON", type:"POST", success:function(result){ $(".queryWeather").html(result.result); } }); }); }); </script> </head> <body> <div> 请输出城市名称:<input class="city" type="text" name="cityname"/><p> <button class="submit" >提交</button><p><p> 你所查询的城市天气情况:<span class="queryWeather"></span> </div> </body> </html>
java文件:
package cn.xdl.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.xdl.util.NetUtil; /** * Servlet implementation class Servlet1 */ @WebServlet("/weather.do") public class Servlet1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); // response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); String city=request.getParameter("cityname"); String result = null; if(city==null || city.length()==0){ //城市没传递 //报错 result = "{\"errorCode\":-1}"; }else{ try { result = NetUtil.toJSON("http://op.juhe.cn/onebox/weather/query","cityname="+city+"&key=633a2171bde0bf871680e74f1455757e"); } catch (Exception e) { //解析聚合服务器的JSON 出现了错误 result = "{\"errorCode\":-2}"; } } response.getWriter().append(result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package cn.xdl.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.json.JSONArray; import org.json.JSONObject; public class NetUtil { /** * 这是一个工具, 可以模拟表单 读取参数1 所指定的网址内容 * @param para * @param url * @return * @throws Exception */ public static String readInterface(String urlStr, String para) throws Exception { //java中的统一资源定位器的抽象表示形式 URL url = new URL(urlStr); //打开连接 , 并获取连接对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //开始连接 : 这个步骤 可以省略 ,会自动进行连接 //conn.connect(); conn.setRequestMethod("POST"); //开启写流 conn.setDoOutput(true); // OutputStream os = conn.getOutputStream(); //转换写流为打印流, 并指定打印的编码格式 PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "utf-8")); //开始向服务器输出一些参数 pw.print(para); pw.close(); InputStream is = conn.getInputStream(); //下面的操作 就是IO阶段的知识点了 , 上面的INputStream就是读取网络地址资源的输入流 //1. 将字节读流,转换为字符流, 并加入缓冲 BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); //2. 循环读取 StringBuffer sb = new StringBuffer(); //每次读取一行, 所存储的临时位置 String text = null; while((text = br.readLine())!=null){ sb.append(text); } br.close(); return sb.toString(); } /** * 专门用来读取天气预报, 转换JSON类型的 * @param url * @return * @throws Exception */ public static String toJSON(String url,String para) throws Exception{ String text = readInterface(url,para); /* * 依次解析json数据 * 注意:取出的每一个名称都应该有对应有字符,因此是使用这种方法之前应该对JSON数据的情况很了解 * 如果需要取的是一个对象,那么应该使用getJSONObject()方法 * 如果需要取得是一个数组,那么应该使用getJSONArray()方法 */ JSONObject obj = new JSONObject(text); JSONObject result = obj.getJSONObject("result"); JSONObject data = result.getJSONObject("data"); JSONArray weather = data.getJSONArray("weather"); JSONObject weather_01 = weather.getJSONObject(0); JSONObject info = weather_01.getJSONObject("info"); //白天的天气 JSONArray day = info.getJSONArray("day"); //晚上的天气 JSONArray night = info.getJSONArray("night"); String dayText = null; if(day.getString(1).equals(night.getString(1))){ dayText = day.getString(1); }else{ dayText = day.getString(1)+"转"+night.getString(1); } return "{\"errorCode\":0,\"result\":[\""+dayText+"\",\""+day.getString(2)+"-"+night.getString(2)+"\"]}"; } }
这里查询的天气的接口是免费的,但是这个接口有连接数量的限制,如果读者得到连接数量达到最大的信息,那么隔天再试就可以了。
标签:定位器 目录结构 info encode 拼接 发送请求 存储 原理 json
原文地址:http://www.cnblogs.com/HDK2016/p/7096234.html