jquery發送請求的各種方法


Jquery發送ajax請求的方法有很多,其中最基本的是$.ajax方法,在其之上封裝的方法有 $.get, $post, $.put, $.ajaxForm, $fileUpload等。而在這些上層的方法中,后兩個為jquery的插件所提供,如果需要用到的話,還需要引入對象的js庫文件。這里我們記錄下各方法的使用及ajax方法最原始的調用方式。

$.get方法:

 1 var params = {"username":"zhangsan","password":"123"};
 2 $.get("/demo",params,function(obj){
 3     console.log(obj);
 4 },"json");
 5 
 6 $.ajax({
 7     type : "GET",
 8     url : 'http://www.baidu.com', 
 9     success : function(html){
10        console.log(html);
11     }
12 });

 

$.post方法:

 1 var params={"username":"zhangsan","password":"1234"};
 2 $.post("/demo",params,function(obj){
 3     console.log(obj);    
 4 },"json");
 5 
 6 $.ajax({
 7     type : "POST",
 8     url : 'http://www.baidu.com/search', 
 9     data : {query : "javascript"},
10     contentType : "application/x-www-form-urlencoded",
11     success : function(data){
12        console.log(data);
13     }
14 });
 1 //提交存json數據
 2 $.ajax({
 3     type : "POST",
 4     url : 'http://www.baidu.com/search', 
 5     data : {query : "javascript"},
 6     contentType : "application/json",
 7     success : function(data){
 8         console.log(data);
 9     }
10 });
1 //提交from數據
2 $.ajax({
3     type : "POST",
4     url : 'http://www.baidu.com/search', 
5     data : $("form").serialize(),    //不帶文件的form表單
6     success : function(data){
7         console.log(data);
8     }
9 });

$.ajaxFrom方法:

 1 $('form').ajaxFrom({
 2     target : '#result',
 3     beforeSubmit : function(formData, jqForm, options){
 4         console.log(options);
 5     },
 6     success : function(responseText, statusText){
 7         console.log(responseText);
 8     }
 9 });
10  
11  
12 $.ajax({      
13     type: 'POST', 
14     url: '/upload',    
15     data: new FormData($('from')[0]),    //帶文件的form表單
16     contentType: false,    
17     processData: false,    
18     success: function (result) {    
19         console.log(result);    
20     },    
21     error: function (err) {    
22         console.log(err);    
23     }    
24 }); 

$.fileupload方法:

 1 $('#fileupload').fileupload({
 2     dataType: 'json',
 3     done: function (e, data) {
 4         console.log(JSON.stringify(data));
 5     }
 6 });
 7  
 8 var fd = new FormData();
 9 fd.append('file', $('#fileupload')[0].files[0]); 
10 fd.append('file2', new File([fileBlob], 'filename.txt')); 
11 $.ajax({      
12     type: 'POST', 
13     url: '/upload',    
14     data: fd,    
15     contentType: false,    
16     processData: false,    
17     success: function (result) {    
18         console.log(result);    
19     },    
20     error: function (err) {    
21         console.log(err);    
22     }    
23 }); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM