Home  >  Article  >  Web Front-end  >  对比分析AngularJS中的$http.post与jQuery.post的区别_AngularJS

对比分析AngularJS中的$http.post与jQuery.post的区别_AngularJS

WBOY
WBOYOriginal
2016-05-16 16:12:461317browse

很多时候我们需要用ajax提交post数据,angularjs与jq类似,也有封装好的post。

但是jQuery的post明显比angularjs的要简单一些,人性化一些。

AngularJS:

复制代码 代码如下:

$http.post('do-submit.php',myData)
.success(function(){
    // some code
});

jQuery:

复制代码 代码如下:

$.post('do-submit.php', myData, function() {
    // some code
});

看起来没什么区别吧?可是,用angularjs的$http提交的数据,在php服务器端却无法通过$_REQUEST/$_POST获取到,而需要用:

复制代码 代码如下:

$params = json_decode(file_get_contents('php://input'),true);

来获取。什么原因呢?

这是因为两者的post对header的处理有所不同……jQuery会把作为JSON对象的myData序列化,例如:

复制代码 代码如下:

var myData = { a : 1, b : 2 };
// jQuery在post数据之前会把myData转换成字符串:"a=1&b=2"

而Angular不会。

解决方案是什么?

1.引入jquery,前提是目标用户不介意多加载一个几十K的脚本。(不推荐)

2.在服务器端(PHP)通过  $params = json_decode(file_get_contents('php://input'),true);   获取参数,小项目可以,大项目要一个一个改。(不推荐)

3.修改Angular的$httpProvider的默认处理:http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/  (为了便于以后的管理,这是最好的办法)

小伙伴们是否对AngularJS中的$http.post与jQuery.post的区别有了进一步的认识了呢,希望大家读完本文能够有所得。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn