前端之家收集整理的这篇文章主要介绍了
ajax动态加载json数据并解析,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<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代码
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,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,age)
PrintWriter out = response.getWriter()
JSONObject jsonObj = JSONObject.fromObject(user)
out.print(jsonObj)
out.flush()
out.close()
}
<script type="text/javascript"> $(document).ready(function() { $('form .get').click(function() { $.get('ajaxServlet',function(response,status,xhr){ var dataObj = eval("(" + response + ")"); $("#Box").html(response); alert(dataObj.name); }); }); $('form .post').click(function() { $.post('ajaxServlet',xhr){ var dataObj = eval("(" + response + ")"); $("#Box").html(response); }); }); $('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,xhr){ $("#Box").html(response);} }); }); }); </script>
原文链接:https://www.f2er.com/ajax/161830.html