-
AJAX
Asynchronous JavaScript and XML
异步的JavaScript与XML,不是一门新技术,只是一个新的术语
使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面
虽然X代表XML,但目前JSON的使用比AJAX更加普遍
-
示例
使用jQuery发送AJAX请求
public class CommunityUtil {
//定义一个返回json字符串的方法
public static String getJSONString(int code, String msg, Map<String,Object> map){
JSONObject json=new JSONObject();
json.put("code",code);
json.put("msg",msg);
//对map进行空判断
if(map!=null){
//遍历map,将每一个键值对放入json
for(String key:map.keySet()){
json.put(key,map.get(key));
}
}
//返回json
return json.toJSONString();
}
//重载上面的json字符串方法(没有业务处理数据的时候,没有map)
public static String getJSONString(int code, String msg){
return getJSONString(code,msg,null);
}
//重载上面的json字符串方法(没有业务处理数据的时候,没有map,没有提示信息的时候,没有msg)
public static String getJSONString(int code){
return getJSONString(code,null,null);
}
public static void main(String[] args) {
Map<String,Object> map=new HashMap<>();
map.put("name","zhangsan");
map.put("age",18);
System.out.println(getJSONString(0,"ok",map));
}
}
2.在视图控制层写一个方法,用来接收客户端的请求,返回得到的json字符串
//ajax示例
@RequestMapping(path = "/ajax",method = RequestMethod.POST)
@ResponseBody
public String testAjax(String name,int age){
System.out.println(name);
System.out.println(age);
return CommunityUtil.getJSONString(0,"操作成功");
}
3.写一个动态的html文件,发送请求,并处理服务器返回来的json字符串
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<p>
<input type="button" value="发送" onclick="send();">
</p>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script>
function send() {
//$.post()有三个参数,第一个是请求路径,第二个是要传递的参数,第三个是回调函数(用来处理服务器返回来的数据)
$.post(
"/community/alpha/ajax",
{"name":"张三","age":23},
function (data) {
console.log(typeof(data))
console.log(data)
data=$.parseJSON(data)
console.log(typeof (data))
console.log(data.code);
console.log(data.msg);
}
);
}
</script>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。