JavaWEB笔记14 jQuery发送AJAX和JAVA后台与JSON数据
文章目录
- JavaWEB笔记14 jQuery发送AJAX和JAVA后台与JSON数据
- 第一部分:jQuery发送AJAX
- 一.jQuery发送AJAX详解:
- 二.jQuery中的其他AJAX封装:
- 三.跨域问题:
- 1.跨域问题介绍:
- 2.跨域请求与解决方案:
- 四.jQuery生成jsonp:
- 第二部分:JAVA后台与JSON数据
- 五.JSON字符串转换成JAVA对象:
- 六.JAVA对象转换成JSON字符串:
- jQuery案例:手机号码归属地查询:
第一部分:jQuery发送AJAX
一.jQuery发送AJAX详解:
AJAX的主要作用指的是在不重新加载页面的情况下,刷新页面中的部分请求,可以将表单提交到后台,其中使用jQuery有多种发送AJAX的方法,现在介绍的是jQuery的原生AJAX:
原生的AJAX之GET请求分为4步:
- 1)创建异步请求对象;
- 2)打开链接发送请求;
- 3)发送请求;
- 4)接收后台响应;
原生的AJAX之POST请求:
发送POST请求之前要设置请求头:setRequestHeader()
来添加HTTP头,然后再用send()
方法中规定你希望发送的数据
POST请求: 提交请求参数,后台使用键值进行比对
jQuery封装之后的AJAX:
jQuery发送AJAX请求:针对设计的button:
$('button').click(function(){ $.ajax({ 内容是jsonobj }) })
详解: 对应上面json对象的详情有:
- 请求方式:
type:"POST" //GET等方式
- 请求的后台地址:
url="some.php"
- 请求参数:
data:"name=Jhon&location=London"
- 后台响应成功的回调函数:
success: function(respData){ console.log(respData) },dataType: "json"; //不加datatype只会转换成字符串而不是对象
其中后台响应成功时使用函数会自动转换成json对象 - 在上面的参数中在请求方式如果是GET时url可以把网址参数拼上去,不写data;如果GET参数不想拼就改为url后面改,后在data中以json对象键值对的形式写
- 请求失败也可以添加参数:
error
进行处理
二.jQuery中的其他AJAX封装:
1)在使用jQuery发送AJAX时,如果AJAX要发送get请求:
$.get(url,data,回调函数,返回类型:"json")
其中可以将对应的回调函数进行展开
2)如果AJAX要发送POST请求:
$.post(url,data,回调函数,,返回类型:"json")
3)直接拿到后台响应的json数据:
$.getJSON(url,data,回调函数)
这三个方法都是比较有针对性的方法,重点记忆AJAX原生的完整方法
三.跨域问题:
1.跨域问题介绍:
跨域问题指的是在请求时无法通过跨域进行访问
跨域问题的产生: 由于浏览器的同源策略(出于安全),在本质上是不存在跨不跨域的,浏览器受限但是一般服务器没有
跨域具体指的是: A网站内部向B网站发送AJAX请求
同源: 协议相同 + 域名相同 + 端口号相同
服务器做了跨域接口之后就可以在前端访问到数据了
2.跨域请求与解决方案:
jQuery发送AJAX时遭遇跨域问题时共有三种处理方法:
- 1)采用JSONP跨域:
特点: 只支持GET请求,其他请求方式不支持
跨域请求原理: 某些标签不受同源浏览器的限制,如:img script link
(除非后台做了防盗链)
JSONP使用的是script进行跨域的: 将对应的填写url的标签设置为script
,注意后面在&
后加上响应成功之后的回调函数的函数名:callback=函数名
JSONP响应: 服务器中将对应的回调函数放入,将对应的返回字符串进行包裹 - 2)主流方法1:cors跨域:
工作原理: 浏览器不会劫持从服务器中重新返来的数据,即:相信浏览器
在后台中设置response.setHeader("Access-Control-Allow-Origin","*")
,即认可全部跨域请求 - 3)主流方法2:代理跨域:
服务器和服务器之间不受同源策略的影响,因此在服务器之间设置一个代理服务器作为当前请求浏览器不跨域的服务器
四.jQuery生成jsonp:
jQuery生成jsonp的方法是在上面之前jQuery对于AJAX的请求模板中:
1)保留
type:"get",url:"..."
2)新增
jsonp:"callback" //jQuery会自动生成一个回调函数,不需要自己命名等
3)保持后面的
success:function(res){ alert(res); }
4)最后
dataType: "jsonp" //后台响应的数据类型
5)注意事项:
后台在响应时就会生成对应的字符串;
如果非要设置回调函数名字:
jsonpCallback: 'haha'
但是在后面要自己写对应的回调函数;
上面更为简单的方法:getJSON发送jsonp:
$.getJSON({ url最后callback=?,function(res){alert(res)}})
第二部分:JAVA后台与JSON数据
五.JSON字符串转换成JAVA对象:
后台要将前台提交上来的JSON字符串转换成JAVA对象,新建一个类并将其中的成员变量对应其键进行数据封装:
处理字符串:
1)去除大括号:
str.replaceAll("\\{","");以及对应的"\\}"
2)截取逗号:
String strings = str.split(",");
然后分别对应strings[]中的不同子字符串
3)截取每一个分段中的冒号:
String[] num = s1.split(":")
4)体力活将上面全部的键值对进行转换
JAVA对象转换成JSON字符串: 拼串
StringBuilder str = new StringBuilder("{");
(str).append("\"").append("name").append("\"").append(":").append(user.getName())
或者直接使用对应的str1+str2
的形式进行拼串
JAVA中提供了一个第三方工具类来完成JSON字符串和JAVA对象的互转: 第三方JSON解析器很多,有:Jsonlib, Gson, fastjson, jackson
我们在这里介绍jackson,与后期的框架中的内置解析器相同,添加第三方jar包的方法:
1)复制第三方jar包到本项目目录下新建一个lib文件夹
2)右键lib点击add as library
用第三方jar包将JSON字符串转换成java对象:
- 1)
String jsonStr="{...}"
定义一个类,类的成员变量名称和数据类型和名称与json字符串中的键保持一致 - 2)调用Jackson方法:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonStr, User.class);
两个参数:json字符串和你定义类中的字节码文件对象
- 3)这种方法的难点在于构造对应的符合层级的类
注意事项:
JSON中出现有如"list":["aaa","bbb"]
的格式的数据时,在新建类时将list设定为集合:
ArrayList<String> list = User.getlist(); //按alt+enter导包
键值嵌套形式:键对应的值是键值对的形式出现的
对于类中键名跨域再设计一个类:
如可以新建Car类:private Car mycar新建一个Car类
安装插件一键生成:
右键Generate
中GsonFormat
中输入对应JSON
,后点左下setting
选择对应的jackson(jack)
,上面的操作在最外层类的设计上进行编辑,而安装插件方法的难点在于安装对应的插件
六.JAVA对象转换成JSON字符串:
简单的方法(体力活):拼串
调用jackson中的方法:
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
//user是对应层级关系最外层的类
当层级嵌套中出现集合或者其他类的情况: 将所有出现的类等进行实例化后再使用上面的生成法则,注意生成双链集合: 生成对应的 HashMap
将生成的JSON字符串保存到文件中:
objectMapper.writeValue(new File("文件名"),map)
在转换时对象中哪个字段不想要转换:
使用注解进行控制:@JsonIgnore
忽略某个字段不想转换成JSON
关于日期字段: 将返还的毫秒值进行格式化年月日时分秒
使用注解进行控制:@JsonFormat(pattern = "yyy-MM-dd HH:mm:ss")
设置对应时区:在上面的括号中的最后加上timezone = "GMT+8"
转换时忽略null值:
添加注解:@JsonInclude(JsonInclude.Include.NON_NULL)
如果是null就不转
转换时将对应字符串中的名字进行动态更改:
使用注解:@JsonProperty("更改后的名字")
jQuery案例:手机号码归属地查询:
案例需求:
设计一个手机号码归属地的查询网页,使用CSS,jQuery封装的AJAX,结合jQuery中的事件或原生dom事件等进行JS动态操作页面
源代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>手机号码归属地专业查询</title>
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
*{
list-style: none;
}
#topElem{
margin-top: 20px;
width: 60%;
margin-left: 20%;
}
#top{
font-size: 40px;
width: 100%;
height: 50px;
line-height: 50px;
text-align: center;
margin-left: -10px;
}
#haomaduan{
font-size: 20px;
margin-top: 25px;
margin-left: 10px;
}
#srch{
border: gray solid 1px;
width: 75%;
height: 36px;
margin-top: 20px;
}
.btn{
width: 100px;
height: 41px;
border: none;
background-color: #3fac24;
color: white;
font-size: 20px;
position: absolute;
left: 65%;
top: 141px;
}
.btn:hover{
cursor: pointer;
}
#bodypart{
position: relative;
width: 66%;
margin-left: 17%;
margin-top: 30px;
}
#chaxjg{
position: absolute;
width: 92%;
height: 45px;
background-color: rgba(154, 150, 143, 0.56);
border: gray solid 1px;
text-align: center;
line-height: 40px;
font-size: 20px;
}
#number{
position: absolute;
top: 47px;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#number_json{
position: absolute;
top: 47px;
left: 46%;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#cityinfo{
position: absolute;
top: 91px;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#cityinfo_json{
position: absolute;
top: 91px;
left: 46%;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#companyinfo{
position: absolute;
top: 135px;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#companyinfo_json{
position: absolute;
top: 135px;
left: 46%;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#cityblock{
position: absolute;
top: 179px;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#cityblock_json{
position: absolute;
top: 179px;
left: 46%;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#postcode{
position: absolute;
top: 223px;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#postcode_json{
position: absolute;
top: 223px;
left: 46%;
border: lightgray solid 1px;
width: 46%;
height: 42px;
text-align: center;
line-height: 45px;
font-size: 18px;
}
#moreinfo{
position: absolute;
top: 267px;
border: lightgray solid 1px;
width: 92%;
height: 50px;
text-align: center;
line-height: 50px;
font-size: 20px;
color: #3fac24;
text-decoration: none;
}
#moreinfo:hover{
cursor: pointer;
}
</style>
</head>
<body>
<div id="topElem">
<div id="top">手机号码归属地专业查询</div>
<div id="haomaduan">手机号码(段):</div>
<input value="" id="srch" type="text" placeholder="请输入需要查询的手机号码"/>
<button type="button" class="btn">查询</button>
</div>
<div id="bodypart" style="visibility: hidden">
<div id="chaxjg">查询结果</div>
<div id="number">您查询的手机号码段</div>
<div id="number_json"></div>
<div id="cityinfo">卡号归属地</div>
<div id="cityinfo_json"></div>
<div id="companyinfo">隶属通讯公司</div>
<div id="companyinfo_json"></div>
<div id="cityblock">区号</div>
<div id="cityblock_json"></div>
<div id="postcode">邮编</div>
<div id="postcode_json"></div>
<a id="moreinfo" href="https://cn.bing.com/search?q=%E4%B8%AD%E5%9B%BD%E5%90%84%E5%9C%B0%E9%82%AE%E7%BC%96%E5%8C%BA%E5%8F%B7&cvid=a2ac39fe100d44c09adb0281ce434de5&aqs=edge..69i57j0.9831j0j1&pglt=41&FORM=ANNTA1&PC=DCTS">更多详情邮编区号</a>
</div>
</body>
<script type="text/javascript">
//绑定点击事件,点击按钮即可搜索
$('button').click(function() {
//展示隐藏起来的查询结果框
var inv = document.getElementById("bodypart");
var attr = document.createAttribute("style");
attr.value = "visibility:visible";
inv.setAttributeNode(attr);
//发送AJAX
var mobile=document.getElementById("srch").value;
var city;
var company;
var block;
var postcode;
$.ajax({
type: "GET",
url : "https://tool.bitefu.net/shouji/?mobile="+mobile,
jsonp: "callback",
success: function(respData) { //后台响应的json字符串,自动帮你转换成JSON对象了
console.log(respData);
mobile = respData.mobile;
city = respData.province+" "+respData.city;
company = respData.isp;
block = respData.areacode;
postcode = respData.postcode;
var text1 = document.getElementById("number_json");
text1.innerText = mobile;
var text2 = document.getElementById("cityinfo_json");
text2.innerText = city;
var text3 = document.getElementById("companyinfo_json");
text3.innerText = company;
var text4 = document.getElementById("cityblock_json");
text4.innerText = block;
var text5 = document.getElementById("postcode_json");
text5.innerText = postcode;
if(respData.info){
alert(respData.info);
text1.innerText = '';
text2.innerText = '';
text3.innerText = '';
text4.innerText = '';
text5.innerText = '';
}
},
dataType:"jsonp"
});
});
</script>
</html>
效果:
未查询时的界面:
查询正常时的界面:
查询输入非法时的界面以及弹窗提醒:
点击弹窗中的确定之后的页面:
点击更多详情之后的页面跳转: