Angular和jQuery的ajax請求的區別,angularjqueryajax
最近項目中使用angular,結果發現後台沒法擷取參數,所以,稍微研究了一下兩者在發送ajax時的區別。注意angular和jquery的ajax請求是不同的。在jquery中,官方文檔解釋contentType預設是 application/x-www-form-urlencoded; charset=UTF-8
- contentType (default:
'application/x-www-form-urlencoded; charset=UTF-8')Type: StringWhen sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
|
而參數data,jquery是進行了轉換的。
- dataType: PlainObject or String or ArrayData to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
|
看下面這段
| Sending Data to the Server
By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param()before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type. |
所以,jquery是javascript對象轉換了字串,傳給後台。在SpringMVC中,就可以使用@RequestParam註解或者request.getParameter()方法擷取參數。
而在angular中,$http的contentType預設值是application/json;charset=UTF-8這樣在後台,SpringMVC通過@RequestParam註解或者request.getParameter()方法是擷取不到參數的。
寫了demo程式。html頁面
| 123456789101112131415161718192021222324252627282930 |
<!DOCTYPE html><html><head> <title></title> <script src="js/jquery.js"></script> <script src="js/angular.js"></script> </head><body ng-app="myApp"><div> <h1>Hello World</h1></div><div> <span>Angular ajax:</span> <a href="#" ng-controller="btnCtrl" ng-click="asave()">Button</a></div> <div> <span>jQuery ajax:</span> <a href="#" id="jBtn">Button</a></div> <div> <span>Angular as jQuery ajax:</span> <a href="#" ng-controller="btnCtrl" ng-click="ajsave()">Button</a></div> </body><script src="js/index.js"></script></html> |
頁面上有三個按鈕:第一個使用angular 的 $http發送ajax請求第二個使用jquery的 $ajax發送ajax請求第三個使用angular的$http方法按照jquery中的方式發送ajax請求
| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
var myApp = angular.module('myApp',[]);var btnCtrl = myApp.controller('btnCtrl',['$scope','$http',function($scope,$http){ $scope.asave = function(){ var user = { name : 'zhangsan', id : '3' } $http({method:'POST',url:'/asave',data:user}).success(function(data){ console.log(data); }) }; $scope.ajsave = function(){ var data = 'namelisi&id=4' $http({ method: 'POST', url: 'ajsave', data: data, // pass in data as strings headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }).success(function (data) { console.log(data); }); }; }]); $('#jBtn').on('click',function(){ $.ajax({ type : 'POST', url : 'jsave', data : {name:'wangwu',id:'5'}, dataType:'json', success : function(data){ console.log(data); } }) }); |
使用angular發送請求(asave方法)時,使用firbug看:
使用jquery發送請求(jsave方法)時,使用firbug看:
所以,如果想用angular達到相同的效果,主要有點:1.修改Content-Type為application/x-www-form-urlencoded; charset=UTF-82.請求參數的格式 key=value的格式,如果,多個,則使用&串連
ajsave方法,經過改造後,用firbug看原始碼
這是前端的發送,那後端使用springmvc接受參數,怎麼處理呢?以前使用jquery,一般使用@RequestParam註解或者request.getParameter方法接受資料。但是使用angular後,這樣是接受不到資料的。如果想接受,可以這樣,定義一個接受的類,要有setter和getter方法。定義User類
| 1234567891011121314151617181920 |
public class User { public String name; public String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; }} |
在Controller中
| 1234567 |
@RequestMapping("/asave") @ResponseBody public String asave(@RequestBody User user){ System.out.println("name---"+user.getName()); System.out.println("id---"+user.getId()); return "ok"; } |
所以,angular預設的這種請求的傳參方式,還得定義一個類,所以,在使用angular發送請求時,可以按照上面說的方法,改成jquery方式,這樣,對於一些簡單參數,擷取就比較方便一些。完整controller代碼:
| 12345678910111213141516171819202122232425262728293031323334 |
@Controllerpublic class MyController { @RequestMapping("/test") @ResponseBody public String test(){ return "hello world"; } @RequestMapping("/asave") @ResponseBody public String asave(@RequestBody User user){ System.out.println("name---"+user.getName()); System.out.println("id---"+user.getId()); return "ok"; } @RequestMapping("/jsave") @ResponseBody public String jsave(@RequestParam String name, @RequestParam String id){ System.out.println("name---"+name); System.out.println("id---"+id); return "ok"; } @RequestMapping("/ajsave") @ResponseBody public String ajsave(@RequestParam String name, @RequestParam String id){ System.out.println("name---"+name); System.out.println("id---"+id); return "ok"; } } |
jquery $ajax $get $post的不同是什噢?
通過 HTTP 要求載入遠端資料。
jQuery 底層 AJAX 實現。簡單易用的高層實現見 $.get, $.post 等。$.ajax() 返回其建立的 XMLHttpRequest 對象。大多數情況下你無需直接操作該函數,除非你需要操作不常用的選項,以獲得更多的靈活性。
最簡單的情況下,$.ajax()可以不帶任何參數直接使用。
注意,所有的選項都可以通過$.ajaxSetup()函數來全域設定。
查看一下API就知道了~!
jquery中的ajax 與 正常的AJAX有什不同
jquery是將原生的js封裝了的
正常寫的話 是需要寫好多代碼判斷是什麼瀏覽器來正確使用不同的ajax版本
jquery已經寫好判斷了的 用$.ajax $.get $.post 甚至JSONP都已經封裝好了的 都不再需要自己寫好多判斷 也不用寫原生js的ajax代碼了的 直接調用就OK