Home > Web Front-end > JS Tutorial > body text

Comparative analysis of the difference between $http.post and jQuery.post in AngularJS_AngularJS

WBOY
Release: 2016-05-16 16:12:46
Original
1344 people have browsed it

Many times we need to use ajax to submit post data. Angularjs is similar to jq and also has encapsulated posts.

But jQuery’s post is obviously simpler and more user-friendly than angularjs’s.

AngularJS:

Copy code The code is as follows:

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

jQuery:

Copy code The code is as follows:

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

Looks like there’s no difference, right? However, the data submitted using $http of angularjs cannot be obtained through $_REQUEST/$_POST on the PHP server. Instead, you need to use:

Copy code The code is as follows:

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

to get it. What's the reason?

This is because the two posts handle headers differently... jQuery will serialize myData as a JSON object, for example:

Copy code The code is as follows:

var myData = { a : 1, b : 2 };
// jQuery will convert myData into a string before posting the data: "a=1&b=2"

And Angular doesn’t.

What’s the solution?

1. Introduce jquery, provided that the target users don’t mind loading an extra tens of K scripts. (Not recommended)

2. Get parameters on the server side (PHP) through $params = json_decode(file_get_contents('php://input'),true);. Small projects can do this, but large projects need to be changed one by one. (Not recommended)

3. Modify the default processing of Angular's $httpProvider: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/ (In order to facilitate future management, this is the best way)

Do you guys have a better understanding of the difference between $http.post and jQuery.post in AngularJS? I hope you will gain something from reading this article.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!