javascript
让AngularJS的$http 服务像jQuery.ajax()一样工作
先比較下他們的差別
$http的post
. 請(qǐng)求默認(rèn)的content-Type=application/json
. 提交的是json對(duì)象的字符串化數(shù)據(jù),
. 后端無(wú)法從post中獲取,
. 跨域請(qǐng)求是復(fù)雜請(qǐng)求,會(huì)發(fā)送OPTIONS的驗(yàn)證請(qǐng)求,成功后才真正發(fā)起post請(qǐng)求
jQuery.post
. 使用的是content-Type=application/x-www-form-urlencoded -
. 提交的是form data,
. 后端可以從post中獲取,
. 簡(jiǎn)單跨域請(qǐng)求,直接發(fā)送
解決辦法有兩個(gè):
1. 是后端支持復(fù)雜的跨域請(qǐng)求
那么后端就需要設(shè)置如下的信息
后端post中拿不到數(shù)據(jù),我們需要自己處理request的body,看看python和php的處理方式:
python
php
<? $params = json_decode(file_get_contents('php://input')); ?>2. 配置AngularJS
配置$http服務(wù)的默認(rèn)content-Type=application/x-www-form-urlencoded,如果是指配置這個(gè)的話(huà),雖然提交的content-Type改了,但是提交的數(shù)據(jù)依然是個(gè)json字符串,不是我們想要的form data形式的鍵值對(duì),需要實(shí)現(xiàn)param方法. Talk is cheap, i show you the code.
配合一點(diǎn)$resource的API參考,這個(gè)代碼就好懂了:
https://docs.angularjs.org/api/ngResource/service/$resource
Note:
上述param方法定義的地方不要使用jQuery.param方法,因?yàn)閖Query.param方法會(huì)將要處理的對(duì)象上的function全執(zhí)行一邊,把返回的值當(dāng)做參數(shù)的值,這是我們不期望的,我們寫(xiě)的這個(gè)param方法也是為了解決上面說(shuō)的content-Type=x-www-form-urlencoded,但是提交的數(shù)據(jù)依然是json串的問(wèn)題。
如果不使用$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/
總結(jié)
以上是生活随笔為你收集整理的让AngularJS的$http 服务像jQuery.ajax()一样工作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Kafka Zero-Copy 使用分析
- 下一篇: 为什么对象字面量没有名字?