今天小编就为大家分享一篇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数据并详细解析
猜你喜欢
- vue keep-alive 2023-10-08
- layui数据表格以及传数据方式 2022-12-13
- 关于 html:如何从 css 表中删除边距和填充 2022-09-21
- ajax实现输入提示效果 2023-02-14
- javascript 判断当前浏览器版本并判断ie版本 2023-08-08
- 基于CORS实现WebApi Ajax 跨域请求解决方法 2023-02-14
- 1 Vue - 简介 2023-10-08
- jsPlumb+vue创建字段映射关系 2023-10-08
- JS实现左侧菜单工具栏 2022-08-31
- 深入浅析AjaxFileUpload实现单个文件的 Ajax 文件上传库 2022-12-15