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);
},
});
參考文獻: