javascript
让AngularJS的$http 服务像jQuery.ajax()一样工作
先比較下他們的差別
$http的post
. 請求默認的content-Type=application/json
. 提交的是json對象的字符串化數據,
. 后端無法從post中獲取,
. 跨域請求是復雜請求,會發送OPTIONS的驗證請求,成功后才真正發起post請求
jQuery.post
. 使用的是content-Type=application/x-www-form-urlencoded -
. 提交的是form data,
. 后端可以從post中獲取,
. 簡單跨域請求,直接發送
解決辦法有兩個:
1. 是后端支持復雜的跨域請求
那么后端就需要設置如下的信息
后端post中拿不到數據,我們需要自己處理request的body,看看python和php的處理方式:
python
php
<? $params = json_decode(file_get_contents('php://input')); ?>2. 配置AngularJS
配置$http服務的默認content-Type=application/x-www-form-urlencoded,如果是指配置這個的話,雖然提交的content-Type改了,但是提交的數據依然是個json字符串,不是我們想要的form data形式的鍵值對,需要實現param方法. Talk is cheap, i show you the code.
配合一點$resource的API參考,這個代碼就好懂了:
https://docs.angularjs.org/api/ngResource/service/$resource
Note:
上述param方法定義的地方不要使用jQuery.param方法,因為jQuery.param方法會將要處理的對象上的function全執行一邊,把返回的值當做參數的值,這是我們不期望的,我們寫的這個param方法也是為了解決上面說的content-Type=x-www-form-urlencoded,但是提交的數據依然是json串的問題。
如果不使用$resource,還有一種方法
$scope.formData = {};$http({method: 'POST',url: '/user/',data: $.param($scope.formData), // pass in data as stringsheaders: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)}).success(function(data) {console.log(data);if (!data.success) {// if not successful, bind errors to error variables$scope.errorName = data.errors.name;$scope.errorSuperhero = data.errors.superheroAlias;} else {// if successful, bind success message to message$scope.message = data.message;}});參考
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
總結
以上是生活随笔為你收集整理的让AngularJS的$http 服务像jQuery.ajax()一样工作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kafka Zero-Copy 使用分析
- 下一篇: 为什么对象字面量没有名字?