Search

JQuery - How to use ajax request

2014-07-30 9:39 PM
Examples

Post

$.ajax("TARGET_URL",
 {
 "type"   : "post",
 "data"   : {"var1" : value1, "var2":value2},
 "success"  : reqeustSuccess,
 "complete"  : requestComplete,
 "error"  : requestFailure}
});

function reqeustSuccess(data, textStatus, jqXHR){
 // request success
}

function requestComplete(jqXHR,textStatus){
 if( textStatus == "success" ){
  // Request success
 }
 else{
  // Request failed
 }
}

function requestFailure(jqXHR, textStatus, errorThrown){
 // request failed
}

Get

$.ajax("TARGET_URL",
 {
 "type"   : "get",
 "data"   : {"var1" : value1, "var2":value2},
 "success"  : reqeustSuccess,
 "complete"  : requestComplete,
 "error"  : requestFailure}
});

function reqeustSuccess(data, textStatus, jqXHR){
 // request success
}

function requestComplete(jqXHR,textStatus){
 if( textStatus == "success" ){
  // Request success
 }
 else{
  // Request failed
 }
}

function requestFailure(jqXHR, textStatus, errorThrown){
 // request failed
}
Details
// Do ajax request. You have to replace the "TARGET_URL" to yours.
$.ajax("TARGET_URL",
 {
// How you do the request. Here you can use "get", "post", "put" or "delete".
// We use "get" and "post" more often. It means "Give me something" and "I Give you something".
// And there are not all browsers can support "put" and "delete" method.
// If you use Java + SpringMVC, then you'll have to working on this problem.
 "type"   : "post",

// The parameters, you can use any string( or something can be converted to String) variable
 "data"   : {"var1" : value1, "var2":value2},

 // The callback function, usually use to notify the user the request is success
 "success"  : reqeustSuccess,

// The callback function, both "success" and "failure" will call this function. You can use it to handle some exceptions.
 "complete"  : requestComplete,

// The callback function, you can use it to notify the user the request was failed.
 "error"  : requestFailure}
});
Links
JQuery 官方網站
ajax說明文件

No comments:

Post a Comment