Make AngularJS $http service behave like jQuery.ajax()(转)

There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) even though the respective manuals imply identical usage. That is, if your jQuery code looked like this before:

(function($) {
  jQuery.post(‘/endpoint‘, { foo: ‘bar‘ }).success(function(response) {
    // ...
  });
})(jQuery);

You may find that the following doesn’t exactly work for you with AngularJS out of the box:

var MainCtrl = function($scope, $http) {
  $http.post(‘/endpoint‘, { foo: ‘bar‘ }).success(function(response) {
    // ...
  });
};

The problem you may encounter is that your server does not appear to receive the { foo: ‘bar‘ } params from the AngularJS request.

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively—that’s a darn shame because AngularJS is certainly not doing anything wrong. By default, jQuery transmits data usingContent-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.

Thankfully, the thoughtful AngularJS developers provided hooks into the $http service to let us impose x-www-form-urlencoded on all our transmissions. There are many solutions people have offered thus far on forums and StackOverflow, but they are not ideal because they require you to modify either your server code or your desired usage pattern of $http. Thus, I present to you the best possible solution, which requires you to change neither server nor client code but rather make some minor adjustments to $http‘s behavior in the config of your app’s AngularJS module:

// Your app‘s root module...
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;
  };

  // Override $http service‘s default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== ‘[object File]‘ ? param(data) : data;
  }];
});

Do not use jQuery.param() in place of the above homegrown param() function; it will cause havoc when you try to use AngularJS $resourcebecause jQuery.param() will fire every method on the $resource class passed to it! (This is a feature of jQuery whereby function members of the object to parametrize are called and the return values are used as the parametrized values, but for our typical use case in AngularJS it is detrimental since we typically pass “real” object instances with methods, etc.)

Now you can go forward with using $http.post() and other such methods as you would expect with existing server code that expects x-www-form-urlencodeddata. Here are a few sample frames of the final result for your day-to-day, end-to-end code (i.e. what you hoped and dreamed for):

The HTML template

<div ng-app="MyModule" ng-controller="MainCtrl">
  <p ng-show="loading">Loading...</p>
  <p ng-hide="loading">Response: {{response}}</p>
</div>

The client code (AngularJS)

var MainCtrl = function($scope, $http) {
  $scope.loading = true;
  $http.post(‘/endpoint‘, { foo: ‘bar‘ }).success(function(response) {
    $scope.response = response;
    $scope.loading = false;
  });
};

The server code (PHP)

<?
header(‘Content-Type: application/json‘);

// Ta-da, using $_POST as normal; PHP is able to
// unserialize the AngularJS request no problem
echo json_encode($_POST);
?>

Other notes

So you may wonder now, is it possible for PHP to read the JSON request from stock AngularJS? Why, of course, by reading the input to PHP and JSON decoding it:

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

Obviously the downside to this is that the code is a little less intuitive (we’re used to $_POST, after all), and if your server-side handlers are already written to rely on$_POST, you will now have to change server code. If you have a good framework in place, you can probably effect a global change such that your input reader will transparently detect JSON requests, but I digress.

Thank you for reading. I hope you enjoyed my first POST. (Get it?!)

时间: 2024-10-02 09:14:19

Make AngularJS $http service behave like jQuery.ajax()(转)的相关文章

jquery ajax跨域的完美解决方法(jsonp方式)

ajax跨域请求的问题,JQuery对于Ajax的跨域请求有两类解决方案,不过都是只支持get方式,接下来为大家详细介绍下客户端JQuery.ajax的调用代码 今天在项目中需要做远程数据加载并渲染页面,直到开发阶段才意识到ajax跨域请求的问题,隐约记得Jquery有提过一个ajax跨域请求的解决方式,于是即刻翻出Jquery的API出来研究,发 JQuery对于Ajax的跨域请求有两类解决方案,不过都是只支持get方式.分别是JQuery的 jquery.ajax jsonp格式和jquer

Jquery Ajax 跨域调用asmx类型 WebService范例

摘要:Ajax 在 Web 2.0 时代起着非常重要的作用,然而有时因为同源策略(SOP)(俗称:跨域问题(cross domain)) 它的作用会受到限制.在本文中,将学习如何克服合作限制.本文以asmx方式搭建webservice作为测试用后端,给出完整的前后端调用解决方案.范例代码. 关键词: jquery ajax 跨域  webservice  asmx  cross-domain 0 问题分析 0.1 什么是跨域问题? 越来越多的网站需要相互协作.例如,在线房屋租赁网站需要谷歌地图的

Jquery ajax 学习笔记

本人的js & jq 一直是菜鸟级别,最近不忙就看了看ajax方面的知识,文中部分内容参考自这里&这里 之前一直用js写ajax现在基于jq实现方便多了~ $.get & $.post 和 $.ajax的区别 之前看过同事写过$.post,而我一直用$.ajax,后来才知道$.get()和$.post()都是通过get和post方式来进行异步,$.ajax()说是jquery最底层的ajax实现的,这里我们使用$.ajax的方式实现. 调用无参方法 1 2 3 4 5 6 7 8

Jquery ajax调用webservice总结

jquery ajax调用webservice(C#)要注意的几个事项: 1.web.config里需要配置2个地方 <httpHandlers>      <remove verb="*" path="*.asmx"/>      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script

jquery ajax实例教程和一些高级用法

jquery ajax的调用方式:jquery.ajax(url,[settings]),jquery ajax常用参数:红色标记参数几乎每个ajax请求都会用到这几个参数,本文将介绍更多jquery ajax实例,后面会有一些ajax高级用法 query ajax的调用方式:jquery.ajax(url,[settings]),因为实际使用过程中经常配置的并不多,所以这里并没有列出所有参数,甚至部分参数默认值,就是最佳实践,根本没必要去自己定义,除非有特殊需求,如果需要所有参数,可以查看jq

使用JQuery的Ajax调用SOAP-XML Web Services(Call SOAP-XML Web Services With jQuery Ajax)(译+摘录)

假设有一个基于.Net的Web Service,其名称为SaveProduct POST /ProductService.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://sh.inobido.com/SaveProduct" <?xml version="1.0" encoding=&qu

Jquery Ajax 调用 WebService

原文:http://www.cnblogs.com/andiki/archive/2010/05/17/1737254.html jquery ajax调用webservice(C#)要注意的几个事项: 1.web.config里需要配置2个地方 <httpHandlers>       <remove verb="*" path="*.asmx"/>       <add verb="*" path="*

实现jquery.ajax及原生的XMLHttpRequest调用WCF服务的方法

废话不多说,直接讲解实现步骤 一.首先我们需定义支持WEB HTTP方法调用的WCF服务契约及实现服务契约类(重点关注各attribute),代码如下: //IAddService.cs namespace WcfService1 { [ServiceContract] public interface IAddService { [OperationContract] [WebInvoke(Method="POST",RequestFormat=WebMessageFormat.Js

利用jquery.ajax()实现跨域

通过jQuery的ajax进行跨域,这其实是采用的jsonp的方式来实现的. jsonp是英文json with padding的缩写.它允许在服务器端生成script tags至返回至客户端,也就是动态生成javascript标签,通过javascript callback的形式实现数据读取. 前端代码如下: $.ajax({ type:"get", async:false, url:"http://192.168.0.168:8080/lightview/filecent