效果圖
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動態(tài)加載json數(shù)據(jù)并詳細(xì)解析就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- jQuery Ajax異步處理Json數(shù)據(jù)詳解
- jQuery使用ajax方法解析返回的json數(shù)據(jù)功能示例
- AJAX和jQuery動態(tài)加載數(shù)據(jù)的實現(xiàn)方法
- 淺析ajax請求json數(shù)據(jù)并用js解析(示例分析)