最近项目中使用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>
页面上有三个按钮:
第一个使用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 和jq 的AJAX的请求区别的更多相关文章

  1. 普通B/S架构模式同步请求与AJAX异步请求区别(个人理解)

    在上次面试的时候有被问到过AJAX同步与异步之间的概念问题,之前没有涉及到异步与同步的知识,所以特意脑补了一下,不是很全面... 同步请求流程:提交请求(POST/GET表单相似的提交操作)---服务 ...

  2. Angular和jQuery的ajax请求的差别

    近期项目中使用angular,结果发现后台没法获取參数,所以,略微研究了一下两者在发送ajax时的差别. 注意angular和jquery的ajax请求是不同的. 在jquery中,官方文档解释con ...

  3. JQ之$.ajax()方法以及ajax跨域请求

    AJAX(Asynchronous javascript AND xml :异步javascript和xml):是一种创建交互式网页应用的网页开发技术.AJAX可以在不重新加载整个页面的情况下与服务器 ...

  4. js中ajax连接服务器open函数的另外两个默认参数get请求和默认异步(open的post方式send函数带参数)(post请求和get请求区别:get:快、简单 post:安全,量大,不缓存)(服务器同步和异步区别:同步:等待服务器响应当中浏览器不能做别的事情)(ajax和jquery一起用的)

    js中ajax连接服务器open函数的另外两个默认参数get请求和默认异步(open的post方式send函数带参数)(post请求和get请求区别:get:快.简单 post:安全,量大,不缓存)( ...

  5. ajax同步请求与异步请求的区别

    ajax 区别: async:布尔值,用来说明请求是否为异步模式.async是很重要的,因为它是用来控制JavaScript如何执行该请求. 当设置为true时,将以异步模式发送该请求,JavaScr ...

  6. vue-d2admin-axios异步请求登录,先对比一下Jquery ajax, Axios, Fetch区别

    先说一下对比吧 Jquery ajax, Axios, Fetch区别之我见 引言 前端技术真是一个发展飞快的领域,我三年前入职的时候只有原生XHR和Jquery ajax,我们还曾被JQuery 1 ...

  7. jq使用ajax请求,返回状态 canceled错误

    在使用jq,ajax请求时出现该错误 原因:button按钮类型为type=submit ,script中又自定用botton按钮点击提交ajax,造成冲突. 解决方法:button按钮类型改为 ty ...

  8. 原生ajax异步请求基础知识

    一.同步交互与异步交互的概念: * 同步交互:客户端向服务器端发送请求,到服务器端进行响应,这个过程中,用户不能做任何其他事情(只能等待响应完才能继续其他请求). * 异步交互:客户端向服务器端发送请 ...

  9. ajax 处理请求回来的数据

    比如接口 /test, 请求方式get, 请求过来的数据要处理在container 里,如下代码 $.get("/test", {}, function(result){ $(&q ...

随机推荐

  1. 微信公众账号开发教程(三) 实例入门:机器人(附源码) ——转自http://www.cnblogs.com/yank/p/3409308.html

    一.功能介绍 通过微信公众平台实现在线客服机器人功能.主要的功能包括:简单对话.查询天气等服务. 这里只是提供比较简单的功能,重在通过此实例来说明公众平台的具体研发过程.只是一个简单DEMO,如果需要 ...

  2. 七 mybatis的延迟加载

    1       延迟加载 1.1     什么是延迟加载 resultMap可以实现高级映射(使用association.collection实现一对一及一对多映射),association.coll ...

  3. BAE3.0上的java+tomcat+hibernate代码发布

    在BAE上使用hibernate说起来也简单,但因为一个不小心,耽误了好几个小时. 百度文档中有说: http://developer.baidu.com/wiki/index.php?title=d ...

  4. ADS报错 Warning : L6301W:Could not find file C:\Program Files . Error : L6218 : Undefined symbol ......

    ADS1.2编译时,出现找不到一个不存在目录下的目标文件(*.o) 编译一个COPY到硬盘上的一个工程,出现以下的fatal error message: Error: (Fatal)L6002: C ...

  5. HBase学习笔记-基础(一)

    HBase版本:0.97 1.Get Gets实在Scan的基础上实现的. 2.联合查询(Join) HBase是否支持联合是一个网上常问问题.简单来说 : 不支持.至少不像传统RDBMS那样支持. ...

  6. 切记CMYK图片格式在IE中将无法显示

    目前为止微软的Internet Explorer 浏览器IE6,IE7,IE8都不支持CMYK颜色模式图像 ,除IE外其他浏览器均能支持!所以大家要注意了 要选择RGB颜色模式,就可以了.

  7. SQL 编辑

    局部变量: DECLARE @variable_name Datatype Variable_naem为局部变量的名称,Datatype为数据名称. 例如: DECLARE @name varchar ...

  8. 使用VC2005编译真正的静态Qt程序

    首先,你应该该知道什么叫静态引用编译.什么叫动态引用编译.我这里只是简单的提提,具体的可以google一下. 动态引用编译,是指相关的库,以dll的形式引用库.动态编译的Exe程序尺寸比较小,因为相关 ...

  9. JS-001-单选复选按钮操作

    此文主要针对 web 页面中常见元素(例如:单选按钮.复选按钮)的 JavaScript 操作,进行简单的源码示例演示,敬请小主们参阅.若有不足之处,敬请大神指正,不胜感激! 话不多言了,直接上码: ...

  10. Java学习-004-传世经典Helloworld

    此文主要通过一个广为人知的传世经典应用(Helloworld)讲述 Java 程序的结构,Java 程序的开发步骤,以及 Java 程序是如何运行的. 一.开发 Java 程序步骤 开发 Java 程 ...