近期项目中使用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: String
    When 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-urlencodedmultipart/form-data,
    or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

而參数data,jquery是进行了转换的。
  • data
    Type: PlainObject or String or Array
    Data 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页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!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>
页面上有三个button:
第一个使用angular 的 $http发送ajax请求
第二个使用jquery的 $ajax发送ajax请求
第三个使用angular的$http方法依照jquery中的方式发送ajax请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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-8
2.请求參数的格式 key=value的格式,假设,多个,则使用&连接

ajsave方法,经过改造后,用firbug看源码


这是前端的发送,那后端使用springmvc接受參数,怎么处理呢?
曾经使用jquery,一般使用@RequestParam注解或者request.getParameter方法接受数据。可是使用angular后,这样是接受不到数据的。
假设想接受,能够这样,定义一个接受的类,要有setter和getter方法。
定义User类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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中
1
2
3
4
5
6
7
@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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Controller
public 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";
    }
 
}



Angular和jQuery的ajax请求的差别的更多相关文章

  1. jQuery发送ajax请求

    利用jquery发送ajax请求的几个模板代码. $.ajax({ async : false, type: 'POST', dataType : "json", url: &qu ...

  2. JQuery发送ajax请求不能用数组作为参数

    JQuery发送ajax请求不能用数组作为参数,否则会接收不到参数, 一.js代码如下: $('#delete-button').click(function(){        var select ...

  3. Jquery发送ajax请求以及datatype参数为text/JSON方式

    Jquery发送ajax请求以及datatype参数为text/JSON方式 1.方式一:datatype:'text' 2.方式二:datatype:'JSON' 3.使用gson-1.5.jar包 ...

  4. 使用es6的then()方法封装jquery的ajax请求

    使用场景: jsp页面中使用jquery的ajax请求比较频繁,以前vue框架的项目用过axios,所以就想着用then()封装一个公共请求的方法,这样每次请求就不用那么麻烦的写一大堆请求参数了. 示 ...

  5. 如何终止JQUERY的$.AJAX请求

    最近遇到,如果用户频繁点击ajax请求,有两个问题: 1,如果连续点击了5个ajax请求,前4个其实是无效的,趁早结束节省资源. 2,更严重的问题是:最后一个发送的请求,响应未必是最后一个,有可能造成 ...

  6. jquery中ajax请求后台数据成功后既不执行success也不执行error解决方法

    jquery中ajax请求后台数据成功后既不执行success也不执行error,此外系统报错:Uncaught SyntaxError: Unexpected identifier at Objec ...

  7. jQuery发送Ajax请求以及出现的问题

    普通jQuery的Ajax请求代码如下: $.ajax({ type: 'POST', url: "http://xxx/yyy/zzz/sendVerifyCode", data ...

  8. Sping MVC不使用任何注解处理(jQuery)Ajax请求(基于XML配置)

    1. Spring Spring框架是一个轻量级的解决方案,是一个潜在的一站式商店,用于构建企业就绪的应用程序.Spring框架是一个Java平台,为开发Java应用程序提供全面的基础架构支持.Spr ...

  9. Struts2处理(jQuery)Ajax请求

    1. Ajax     Ajax(Asynchronous JavaScript and XML,异步JavaScript和XML)时一种创建交互式网页应用的网页开发技术,它并不是一项新的技术,其产生 ...

随机推荐

  1. javascript技巧合集

    转http://www.blogjava.net/zhaochengming/archive/2010/04/09/317837.html http://www.cnblogs.com/fxgachi ...

  2. java中遍历List中的map问题

    List list = new ArrayList();Map map = null; while (rs.next()) { map = new HashMap(); map.put("f ...

  3. MySQL主从复制中断处理一例

    收到mysql主从中断报警邮件,马上登上服务器查看,发现是中继日志损坏. Show slave status\G,提示中继日志损坏,按以往的做法,根据提示重新指定合适的日志文件以及pos点.  Rel ...

  4. UltraEdit (Ctrl + F) 查找、(Ctrl + R)替换功能失效

    环境: Windows 7 Service Pack 1 X64 工具: UltraEdit Version 21 症状: UltraEdit (Ctrl + F) 查找.(Ctrl + R)替换功能 ...

  5. Android开发UI之android:gravity / android:layout_Gravity,android:padding / android:layout_margin属性区分

    android:gravity / android:layout_Gravity区别: android:gravity 是设置该view里面的内容相对于该view的位置,例如设置button里面的te ...

  6. 实验一DOS报告

    实验一.DOS命令解释程序的编写实验 13物联网  李名贵  201306104123 一.        实验目的 (1)认识DOS: (2)掌握命令解释程序的原理: (3)掌握简单的DOS调用方法 ...

  7. URAL1012. K-based Numbers. Version 2

    链接 考查大数 正好拿来学习下JAVA JAVA好高端.. import java.io.*; import java.math.*; import java.text.*; import java. ...

  8. [HDU 1565+1569] 方格取数

    HDU 1565 方格取数(1) Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  9. DD_belatedPNG,IE6下PNG透明解决方案

    我们知道IE6是不支持透明的PNG的,这无疑限制了网页设计的发挥空间. 然而整个互联网上解决这个IE6的透明PNG的方案也是多不胜数,从使用IE特有的滤镜或是e­xpression,再到javascr ...

  10. Mac常用目录

    服务存放目录: ~/Library/Services/ Xcode代码片段目录 ~/Library/Developer/Xcode/UserData/CodeSnippets