日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

让AngularJS的$http 服务像jQuery.ajax()一样工作

發(fā)布時間:2025/7/14 javascript 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 让AngularJS的$http 服务像jQuery.ajax()一样工作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

先比較下他們的差別

  • $http的post
    . 請求默認的content-Type=application/json
    . 提交的是json對象的字符串化數(shù)據(jù),
    . 后端無法從post中獲取,
    . 跨域請求是復(fù)雜請求,會發(fā)送OPTIONS的驗證請求,成功后才真正發(fā)起post請求

  • jQuery.post
    . 使用的是content-Type=application/x-www-form-urlencoded -
    . 提交的是form data,
    . 后端可以從post中獲取,
    . 簡單跨域請求,直接發(fā)送

  • 解決辦法有兩個:

    1. 是后端支持復(fù)雜的跨域請求
    那么后端就需要設(shè)置如下的信息

    def options(self):self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')self.set_header('Access-Control-Max-Age', 86400)self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')self.write('')

    后端post中拿不到數(shù)據(jù),我們需要自己處理request的body,看看python和php的處理方式:
    python

    #這種寫法支持多種content-Type提交def POST(self):if self.request.headers['Content-Type'].find('application/json') >= 0:body = self.request.bodyif body:return json.loads(body.decode())else:return {} else: paras = {}for k, v in self.request.body_arguments.items():paras[k] = v[-1].decode()return paras

    php

    <? $params = json_decode(file_get_contents('php://input')); ?>

    2. 配置AngularJS
    配置$http服務(wù)的默認content-Type=application/x-www-form-urlencoded,如果是指配置這個的話,雖然提交的content-Type改了,但是提交的數(shù)據(jù)依然是個json字符串,不是我們想要的form data形式的鍵值對,需要實現(xiàn)param方法. Talk is cheap, i show you the code.

    angular.module('MyModule', [], function($httpProvider) {// Use x-www-form-urlencoded Content-Type$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';/*** The workhorse; converts an object to x-www-form-urlencoded serialization.* @param {Object} obj* @return {String}*/var param = function(obj) {var query = '',name, value, fullSubName, subName, subValue, innerObj, i;for (name in obj) {value = obj[name];if (value instanceof Array) {for (i = 0; i < value.length; ++i) {subValue = value[i];fullSubName = name + '[' + i + ']';innerObj = {};innerObj[fullSubName] = subValue;query += param(innerObj) + '&';}} else if (value instanceof Object) {for (subName in value) {subValue = value[subName];fullSubName = name + '[' + subName + ']';innerObj = {};innerObj[fullSubName] = subValue;query += param(innerObj) + '&';}} else if (value !== undefined && value !== null)query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';}return query.length ? query.substr(0, query.length - 1) : query;};//一個function數(shù)組,負責將請求的body,也就是post data,轉(zhuǎn)換成想要的形式// Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function(data) {return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;}]; });

    配合一點$resource的API參考,這個代碼就好懂了:
    https://docs.angularjs.org/api/ngResource/service/$resource

    Note:
    上述param方法定義的地方不要使用jQuery.param方法,因為jQuery.param方法會將要處理的對象上的function全執(zhí)行一邊,把返回的值當做參數(shù)的值,這是我們不期望的,我們寫的這個param方法也是為了解決上面說的content-Type=x-www-form-urlencoded,但是提交的數(shù)據(jù)依然是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/

    總結(jié)

    以上是生活随笔為你收集整理的让AngularJS的$http 服务像jQuery.ajax()一样工作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。