Search

JQuery - How to use ajax request

2014-07-30 9:39 PM
Examples

Post

  1. $.ajax("TARGET_URL",
  2. {
  3. "type" : "post",
  4. "data" : {"var1" : value1, "var2":value2},
  5. "success" : reqeustSuccess,
  6. "complete" : requestComplete,
  7. "error" : requestFailure}
  8. });
  9.  
  10. function reqeustSuccess(data, textStatus, jqXHR){
  11. // request success
  12. }
  13.  
  14. function requestComplete(jqXHR,textStatus){
  15. if( textStatus == "success" ){
  16. // Request success
  17. }
  18. else{
  19. // Request failed
  20. }
  21. }
  22.  
  23. function requestFailure(jqXHR, textStatus, errorThrown){
  24. // request failed
  25. }

Get

  1. $.ajax("TARGET_URL",
  2. {
  3. "type" : "get",
  4. "data" : {"var1" : value1, "var2":value2},
  5. "success" : reqeustSuccess,
  6. "complete" : requestComplete,
  7. "error" : requestFailure}
  8. });
  9.  
  10. function reqeustSuccess(data, textStatus, jqXHR){
  11. // request success
  12. }
  13.  
  14. function requestComplete(jqXHR,textStatus){
  15. if( textStatus == "success" ){
  16. // Request success
  17. }
  18. else{
  19. // Request failed
  20. }
  21. }
  22.  
  23. function requestFailure(jqXHR, textStatus, errorThrown){
  24. // request failed
  25. }
Details
  1. // Do ajax request. You have to replace the "TARGET_URL" to yours.
  2. $.ajax("TARGET_URL",
  3. {
  4. // How you do the request. Here you can use "get", "post", "put" or "delete".
  5. // We use "get" and "post" more often. It means "Give me something" and "I Give you something".
  6. // And there are not all browsers can support "put" and "delete" method.
  7. // If you use Java + SpringMVC, then you'll have to working on this problem.
  8. "type" : "post",
  9.  
  10. // The parameters, you can use any string( or something can be converted to String) variable
  11. "data" : {"var1" : value1, "var2":value2},
  12.  
  13. // The callback function, usually use to notify the user the request is success
  14. "success" : reqeustSuccess,
  15.  
  16. // The callback function, both "success" and "failure" will call this function. You can use it to handle some exceptions.
  17. "complete" : requestComplete,
  18.  
  19. // The callback function, you can use it to notify the user the request was failed.
  20. "error" : requestFailure}
  21. });
Links
JQuery 官方網站
ajax說明文件

No comments:

Post a Comment