今天小编就为大家分享一篇ajax动态加载json数据并详细解析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
效果图
jsp代码
<form >
姓名:<input name="name" type="text"/>
年龄:<input name="age" type="text"/>
<input type="button" class="get" value="get提交"/>
<input type="button" class="post" value="post提交"/>
<input type="button" class="ajax" value="ajax提交"/>
</form>
<div id="box"></div>
servlet代码
//get
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
if (name == null || name == "") {
name = "测试名字admin";
}
if (age == null || age == "") {
age = "测试年龄100";
}
user user = new user(1, name, age);
PrintWriter out = response.getWriter();
JSONObject jsonObj = JSONObject.fromObject(user);
out.print(jsonObj);
out.flush();
out.close();
}
//post
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("name");
if (name == null || name == "") {
name = "测试名字admin";
}
String age = request.getParameter("age");
if (age == null || age == "") {
age = "测试年龄100";
}
user user = new user(1, name, age);
PrintWriter out = response.getWriter();
JSONObject jsonObj = JSONObject.fromObject(user);
out.print(jsonObj);
out.flush();
out.close();
}
JS核心代码
<script type="text/javascript">
//get
$(document).ready(function() {
$('form .get').click(function() {
$.get('ajaxServlet',function(response,status,xhr){
var dataObj = eval("(" + response + ")");
$("#box").html(response);
alert(dataObj.name);
});
});
//post
$('form .post').click(function() {
$.post('ajaxServlet',function(response,status,xhr){
var dataObj = eval("(" + response + ")");
$("#box").html(response);
});
});
//ajax
$('form .ajax').click(function() {
alert($("[name='name']").val());
$.ajax({
type:'get',
url:'ajaxServlet',
data:{
name:$("[name='name']").val(),
age:$("[name='age']").val()
},
success:function(response, status, xhr){
$("#box").html(response);}
});
});
});
</script>
以上这篇ajax动态加载json数据并详细解析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:ajax动态加载json数据并详细解析
基础教程推荐
猜你喜欢
- 关于 css:WebKit (iPad) CSS3: 背景过渡闪烁 2022-09-21
- 深入浅析Jsonp解决ajax跨域问题 2022-12-28
- Vue+WebSocket实现在线聊天 2023-10-08
- 第7天:CSS入门 2022-11-04
- ExtJS 3.x DateField menuListeners 显示/隐藏 2022-09-15
- 解决ajax的delete、put方法接收不到参数的问题方法 2023-02-23
- vue的 Mixins (混入) 2023-10-08
- ECSHOP中实现ajax弹窗登录功能 2023-01-31
- 分页技术原理与实现之无刷新的Ajax分页技术(三) 2023-01-20
- 基于bootstrap的上传插件fileinput实现ajax异步上传功能(支持多文件上传预览拖拽) 2023-02-01