ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Ajax概念 异步提交,局部刷新 同步提交:Form提交,串行,全页刷新。 异步提交:ajax提交,并行, 局部刷新 Ajax问题1:局部刷新的代码是由js操作,js操作比较多。 问题2:浏览器导航的前进后退不能使用。 # Json数据格式 对象:{} 定界, 属性用,分割, 属性名和属性值之间用:分割 属性名:“”定界 属性值: json 数据类型String, 数字类型(正数和小数都行), Boolean: true, false 对象:{“cityid”:024,”cityname”:”沈阳”} 集合:[{“cityid”:024,”cityname”:”沈阳”},{cityid”:0411,”cityname”:”大连”}] # 案例1: 省市联动 get提交 服务器端代码 ~~~ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取省的id String pid = request.getParameter("pid"); //2.根据id获得city列表(List) //3.把List -> json字符串转换 String jsonstr = ""; if(pid.equals("1")) { jsonstr = "[{\"cityid\":\"024\",\"cityname\":\"沈阳\"},{\"cityid\":\"0411\",\"cityname\":\"大连\"}]"; } else if(pid.equals("2")) { jsonstr = "[{\"cityid\":\"011\",\"cityname\":\"长春\"},{\"cityid\":\"022\",\"cityname\":\"四平\"}]"; } //4.通过reponse对象,把json字符串反馈给客户端 //设置响应编码 response.setCharacterEncoding("utf-8"); //设置响应类型 response.setContentType("text/plain");//ContentType MIME类型 PrintWriter out = response.getWriter(); //发 out.write(jsonstr); //关闭流 out.flush(); out.close(); } ~~~ 客户端代码 ~~~ $("#province").change(function(){ //1. 选的省 var province = $(this).val(); //2. 发送ajax请求 //url: 绝对路径,/开头,/代表ip:port /工程名/ServletURL路径 // 相对路径,不以/开头, 相对当前浏览器地址 //success:服务器正常响应 //error: 服务器错误 404,500,服务器返回的字符串不符合json格式,{"msg":xxx} $.ajax({ url:"GetCityServlet?pid="+province, type:"get", dataType:"json", success:function(data) { $("#city")[0].options.length = 1; console.log(data); //更新city列表 for(var i=0; i<data.length; i++) { $("#city").append('<option value="'+data[i].cityid+'">'+data[i].cityname+'</option>'); } }, error:function(err) { console.log(err); } }); }); ~~~ post提交 # 案例2: 检查用户名是否重复 服务器端代码 ~~~ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 得到用户名 String username = request.getParameter("username"); //2. 假设已有用户名admin, feiyy String jsonstr = ""; if(username.equals("admin") || username.equals("feiyy")) { //3. 给客户端反馈 {"result",true} jsonstr = "{\"result\":true}"; } else { //3. 给客户端反馈 {"result",false} jsonstr = "{\"result\":false}"; } //给客户端反馈 //设置响应编码 response.setCharacterEncoding("utf-8"); //设置响应类型 response.setContentType("text/plain");//ContentType MIME类型 PrintWriter out = response.getWriter(); //发 out.write(jsonstr); //关闭流 out.flush(); out.close(); } ~~~ 客户端代码 ~~~ $.ajax({ url:"CheckNameServlet", type:"post", data:{username:$(this).val()}, dataType:"json", cache:false, success:function(data) { if(data.result) { $("#msg").html("用户名已经被占用") } else { $("#msg").html("用户名可用") } }, error:function(err) { console.log(err); } }); ~~~ # ajax 2.0特性 ~~~ var formData = new FormData($("#myform")[0]); $.ajax({ url:"../EditSelfServlet", type:"post", data:formData, dataType:"json", contentType:false, processData:false, success:function(data) { } }); ~~~ 注意: 1. 页面上, 让表单以二进制方式提交 <form id="myform" method="post" enctype="multipart/form-data"> 2. 后台代码上,以二进制方式处理 Servlet3.0简单,@MultipartConfig注解 Servlet2.5复杂, 使用appache commons fileupload方式获取表单数据 # Gson 处理对象<->Json互转 Gson(chrome), fastjson(阿里巴巴), jackson(Spring MVC) 对象-》 json字符串 Object -> {} List -> [{},{}] json字符串 -》 对象 样例1 ~~~ //City -> str public static void test1() { City c = new City(); c.setCityid("024"); c.setCityname("沈阳"); //{"cityid":"024","cityname":"沈阳"}; //创建Gson对象 Gson gson = new Gson(); String jsonstr = gson.toJson(c); System.out.println(jsonstr); } ~~~ 样例2: ~~~ //City List -> str public static void test2() { List<City> list = new ArrayList<>(); City c = new City(); c.setCityid("024"); c.setCityname("沈阳"); City c2 = new City(); c2.setCityid("0411"); c2.setCityname("大连"); list.add(c); list.add(c2); //[{"cityid":"024","cityname":"沈阳"},{"cityid":"0411","cityname":"大连"}] //创建Gson对象 Gson gson = new Gson(); String jsonstr = gson.toJson(list); System.out.println(jsonstr); } ~~~ 样例3 ~~~ //str -> City public static void test3() { String str = "{\"cityid\":\"024\",\"cityname\":\"沈阳\"}"; //创建Gson对象 Gson gson = new Gson(); City c = gson.fromJson(str, City.class); System.out.println(c.getCityid()+"\t"+c.getCityname()); } ~~~ 样例4: ~~~ //str -> City List public static void test4() { String str = "[{\"cityid\":\"024\",\"cityname\":\"沈阳\"},{\"cityid\":\"0411\",\"cityname\":\"大连\"}]"; //创建Gson对象 Gson gson = new Gson(); //List<City> List<City> list = gson.fromJson(str, new TypeToken<List<City>>(){}.getType()); System.out.println(list.size()); } ~~~ # 案例3:图灵聊天机器人 ~~~ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="js/jquery-3.2.0.min.js"></script> <script> $(function(){ $("#btn_send").click(function(){ //把自己发送的消息放在消息区域里。 $("#panel").append('<p>我:'+$("#msg").val()+'</p>'); $.ajax({ url:"http://www.tuling123.com/openapi/api?key=fb6b7bcfbe52fccdb7f5d752a3088f75&info="+$("#msg").val(), dataType:"json", cache:false, success:function(data) { $("#panel").append('<p>图灵:'+data.text+'</p>'); } }); }); }) </script> <style> #panel { width:100%; height:600px; border:1px solid #ccc; overflow:auto; } #msgdiv { margin-top:20px; } #msgdiv>textarea { width:100%; height:100px; resize:none; } </style> </head> <body> <div id="panel"> </div> <div id="msgdiv"> <textarea id="msg"></textarea> </div> <button id="btn_send" type="button">发送</button> </body> </html> ~~~ # ajax跨域 跨域问题来源于javascript的同源策略,协议+ip+端口相同,就叫做同源,如果html要访问的资源,协议+ip+端口不相同,就叫做跨域了。 跨域: html ajax 请求到其他服务器上的资源 http://www.taobao.com/xxServlet 解决方式1: 在服务器端允许跨域 xxServlet,给客户端反馈之前 设置头信息 response.setHeader("Access-Control-Allow-Origin", "*"); 问题:1)改服务器端代码 解决方式2: jsonp 利用了script标签的跨域能力 callback=getinfo 服务器端有代码配合 getinfo(xxx) 问题: 1)服务器端的配合 解决方式3: 本地服务器中转 ajax->本地服务器->外部服务器 或者nginx反向代理 问题:需要编写服务器中转代码 或者搭建nginx jsonp的原理: ~~~ <!DOCTYPE HTML> <html id="myhtml"> <head> <title>test6.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script src="jquery-3.1.0.min.js"></script> </head> <body> 电话号码:<input id="tel" type="text" /> <br><a href="#">省:</a><span id="provice"></span> <br>类型:<span id="type"></span> </body> <script> $('#tel').blur(function(){ $("#schange").remove(); $("#provice").empty(); $("#type").empty(); var tel = $('#tel').val(); var telnump = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel='; var telnumb = '&callback=getresult'; var telnum = telnump+tel+telnumb; var obj = document.createElement("script"); obj.id = "schange"; obj.src = telnum; document.getElementById("myhtml").appendChild(obj); }) function getresult(data) { $("#provice").html(data.province); $("#type").html(data.catName); } </script> </html> ~~~ # 案例4:手机归属地查询 ~~~ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>test7.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script src="jquery-3.1.0.min.js"></script> </head> <body> 电话号码:<input id="tel" type="text" /> 省<span id="provice"></span> 类型<span id="type"></span> </body> <script> //自运行函数 (function(){ $(window).keydown(function(event){ //回车键 if(event.keyCode == 13) { $.ajax({ url:"https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="+$("#tel").val(), dataType:"jsonp", jsonp:"callback", success:function(data) { $("#provice").html(data.province); $("#type").html(data.catName); } }); } }); })(); </script> </html> ~~~ # 案例5:手机天气(采用服务器中转) 自己编写servlet,发送http请求获取数据,返给ajax 服务器端: ~~~ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String city = request.getParameter("city"); String str = sendGetRequest("https://api.seniverse.com/v3/weather/now.json?key=0xwo33idzypm5gb7&location="+city+"&language=zh-Hans&unit=c"); //把str反馈给ajax response.setCharacterEncoding("utf-8"); response.setContentType("utf-8"); PrintWriter out = response.getWriter(); out.write(str); out.flush(); out.close(); } ~~~ ~~~ public String sendGetRequest(String getUrl) { StringBuffer sb = new StringBuffer(); InputStreamReader isr = null; BufferedReader br = null; try { URL url = new URL(getUrl); //URLConnection urlConnection = url.openConnection(); //urlConnection.setAllowUserInteraction(false); isr = new InputStreamReader(url.openStream(),"utf-8"); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } ~~~ 客户端 ~~~ $("#city").blur(function(){ $.ajax({ url:"GetCellPhoneServlet?city="+$("#city").val(), dataType:"json", success:function(data) { console.log(data.results[0].now.temperature); }, error:function(err) { console.log(err); } }); }); ~~~