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 });