热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

angular和jq的AJAX的请求区别

最近项目中使用angular,结果发现后台没法获取参数,所以,稍微研究了一下两者在发送ajax时的区别。注意angular和jquery的ajax请求是不同的。在jquery中,官
最近项目中使用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
<html>
<head>
    <title>title>
    <script src="js/jquery.js">script>
    <script src="js/angular.js">script>
 
head>
<body ng-app="myApp">
<div>
    <h1>Hello Worldh1>
div>
<div>
    <span>Angular ajax:span>
    <a href="#" ng-controller="btnCtrl" ng-click="asave()">Buttona>
div>
 
<div>
    <span>jQuery ajax:span>
    <a href="#" id="jBtn">Buttona>
div>
 
<div>
    <span>Angular as jQuery ajax:span>
    <a href="#" ng-controller="btnCtrl" ng-click="ajsave()">Buttona>
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看:
技术分享
技术分享
技术分享
这是前端的发送,那后端使用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的请求区别


推荐阅读
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • CentOS 6.5安装VMware Tools及共享文件夹显示问题解决方法
    本文介绍了在CentOS 6.5上安装VMware Tools及解决共享文件夹显示问题的方法。包括清空CD/DVD使用的ISO镜像文件、创建挂载目录、改变光驱设备的读写权限等步骤。最后给出了拷贝解压VMware Tools的操作。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
author-avatar
波波无敌1989_424
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有