In JQuery, there are three ways to implement AJAX: $.ajax(), $.post, $.get().
First we look at $.get():
$.get("test.jsp",
{ name: "cssrain", time: "2008/01/21" }, //Data to be passed
function(data){
alert( "Returned data: " data);
}
)
Then look at $.post():
The format is the same as $.get().
$.post("test.jsp",
{ name: "cssrain", time: "2008/01/21" }, //Data to be transferred
function(data){
alert("Returned data: " data);
}
)
The difference between the above two methods should be the different request methods (one get and one post).
Finally we look at $.ajax():
$.ajax({
url:'Accept.jsp',
type:' post', //Data sending method
dataType:'html', //Accept data formats (there are many here, commonly used ones are html, xml, js, json)
data:'text=' $(" #name").val() '&date=' new Date(), //Data to be passed
error: function(){ //Failure
alert('Error loading document');
},
success: function(msg){ //Success
alert( "Data Saved: " msg );
}
});
Instance
The code for the front-end jsp part is as follows:...
Number of votes:
...
The code for the js part is as follows
function myvote(id){
$.post("vote. jsp", { id: id },
function(data){
eval("var data=" data);
if (data.issucc=="0"){
alert( data.mess)
}else{
//alert("Update page");
$("#i" data.myid).html(data.votenum);
}
});
}
The returned data is json
The json data returned by the background is as follows
{issucc:,mess:””,votenum:,myid:}
issucc: whether it was successful
mess: information, mainly error information, such as not logged in, exceeding the limit, etc.
votenum: the total number of votes after voting
myid: the id of the vote, used to update the number of votes on the page
A registration login instance
js
The type returned by login.jsp is in the form of text, which is "OK" when it is correct, and
"error" when it is wrong.
var userName;
var password;
var result;
$(document).ready(function(){
$("#load").hide();
$("#success").hide();
$("#error").hide();
});
$(document).ready(function(){
$("#button").click(function(){
$("#error").hide();
$("#load").show("slow");
userName = $("#userName").val();
password = $("#password").val();
$.ajax({type: "post",
url: "login.jsp",
dataType: "html",
data: "userName=" userName "&password=" password,
success: function(result){
var res = String($.trim(result));
if(res== "OK"){
$("#myTable").hide("slow");
$("#success").show("slow");
}else if(res= ="error"){
$("#error").show("slow");
$("#load").hide("slow");
}else{
alert("Exception returned");}
}
});
});
});
jsp page
First responseText Format
<%@ page language="java" pageEncoding ="gb2312"%>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if(password. equals("longleg")&&userName.equals("thy")){
out.print("OK");
}else{out.print("error");}
%>