ajax可以發送post或者get請求,並且可以設定同步或者非同步,這裡羅列了幾種。其中,幕後處理請求由servlet實現。
第一種方式:
var xmlhttp = new XMLHttpRequest();//發送post請求,false表示發送同步請求xmlhttp.open("POST","AdminLogin",false);//設定檔案的頭,UTF-8應與html編碼格式一致,告訴瀏覽器對參數編碼的格式,可以解決中文傳輸亂碼的問題xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");//設定傳遞的參數xmlhttp.send("id="+id+"&password="+password);//顯示返回結果alert(xmlhttp.responseText);
第二種方式(接受JSON包):
//使用ajax方法,JS代碼$.ajax({ url: "GetStudentInfo", type: 'POST', async: false, contentType: 'application/json', mimeType: 'application/json', success: function (data) {//對傳回值的處理$("#id").val(data.id);$("#name").val(data.name);$("#year").val(data.year);$("#specialty").val(data.specialty);$("#phone").val(data.phone);$("#email").val(data.email); },});
//Servlet代碼public class User {public String id;public String name;public String year;public String specialty;public String phone;public String email;}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ObjectMapper mapper = new ObjectMapper(); Connection con = DBTool.getConnection();User u = new User();u.id = "a";u.name = "b";u.year = "c";u.specialty = "d";u.phone = "e";u.email = "f";response.setContentType("application/json"); }
第三種方式(接受JSON包,返回值為集合):
//JS代碼$.ajax({ url: "CheckAllStudent", type: 'POST', contentType: 'application/json', mimeType: 'application/json', success: function (data) { $.each(data, function (index, student) { var string = "<tr>"; string += "<td>" + student.id+ "</td>"; string += "<td>" + student.name+ "</td>"; string += "<td>" + student.year+ "</td>"; string += "<td>" + student.specialty+ "</td>"; string += "<td>" + student.phone+ "</td>"; string += "<td>" + student.email+ "</td>"; $("tbody").append(string); }); },});
//Servlet代碼protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); //把相同的對象放入List中 List<User>list = new ArrayList<User>(); User u1,u2,u3; list.add(u1); list.add(u2); list.add(u3);response.setContentType("application/json"); mapper.writeValue(response.getOutputStream(), list);}
第四種方式(ajax方法,帶參數):
$.ajax({url: "ShowAdvertise",type: 'POST',data: {time:time},success: function(data) {alert(data);},});
參考文獻:
jQuery ajax - ajax() 方法