[Angularjs] $http. Post and $.post

Source: Internet
Author: User

Summary

When Angularjs sends a POST request, it is really confusing, when passing JSON data, always encountered in the server can not accept parameters, it is necessary to compare with $.post to learn.

An example

Here to simulate a scene of login, post user name and password, the server accepts the account and returns directly to the client without doing other business processing.

Using the ANGULARJS version

/* AngularJS v1.2.15 (c) 2010-2014 Google, Inc. http://angularjs.org license:mit */

Service side

     Public classAccountcontroller:controller {//GET:/<controller>/         PublicIactionresult Login () {returnView (); } [HttpPost] PublicIactionresult Login (stringUserName,stringuserpwd) {            varResut =Request.Form; returnJson (New{_code = $, _msg ="Login Success", name = userName, password =userpwd}); }    }

$.post

First use $.post to submit your account password directly

   $.post ("@Url. Content ("~/account/login")""  2342342", Userpwd:"2sssdfs"  },function (data) {            Console.log (data);        });

Response

Here we look at the request body

So now we look at the situation of Angularjs's $http.post, what is the difference?

@{Layout = null;}<!DOCTYPE HTML><HTMLNg-app= "Login"><Head>    <Metaname= "Viewport"content= "Width=device-width, initial-scale=1.0" />    <title>It strange o user Login</title>    <Linkhref= "~/lib/bootstrap/dist/css/bootstrap.css"rel= "stylesheet" />    <Scriptsrc= "~/js/angular.min.js"></Script>    <Script>Angular.module ("Login", []). Controller ("Logincontroller", function($http, $scope) {$scope. Login= function () {                varData={userName: $scope. UserName, Userpwd: $scope. userpwd}; varConfig={headers: {'Content-type': 'application/x-www-form-urlencoded' },                    //transformrequest:function (obj) {                    //var str = [];                    //For (var p in obj) {                    //Str.push (encodeURIComponent (p) + "=" + encodeURIComponent (Obj[p]));                    //    }                    //return Str.join ("&");                    //}                };                Console.log (data); $http. Post ("@Url. Content ("~/ Account/Login")", data, config). Success (function(data) {Console.log (data);            });        };    }); </Script></Head><Body>    <DivNg-controller= "Logincontroller">        <inputtype= "text"placeholder= "User name"Ng-model= "UserName"value="" />        <inputtype= "Password"placeholder= "Password"Ng-model= "Userpwd"value="" />        <ButtonNg-click= "Login ()">Login</Button>    </Div></Body></HTML>

Login

Appeared, in the habit of reason, usually will write $http.post. But the result is not what you want. So let's compare the request body with $.post.

Did you see that? The difference is right here.

When we find the problem, we are going to convert it into the way $.post submits the parameters. Fortunately, Angularjs $http.post provides a transformrequest method for conversion parameters that can be added to config:

   var config = {                    headers: {' content-type ': ' application/x-www-form-urlencoded '},                    transformrequest:function ( obj) {                        var str = [];                        For (var p in obj) {                            str.push (encodeURIComponent (p) + "=" + encodeURIComponent (Obj[p]));                        }                        Return Str.join ("&");                    }                ;

Its role is to convert the submitted parameters into $.post submission parameters. In this case, the parameters in the request body are identical to the $.post.

can be set globally

<script>Angular.module ("Login", []). Controller ("Logincontroller",function($http, $scope) {$scope. Login=function () {                vardata ={userName: $scope. UserName, Userpwd: $scope. userpwd};                Console.log (data); $http. Post ("@Url. Content (" ~/account/login ")", data). Success (function(data) {Console.log (data);            });        }; }). config (function($httpProvider) {$httpProvider. defaults.transformrequest=function(obj) {varstr = [];  for(varPinchobj) {Str.push (encodeURIComponent (p)+ "=" +encodeURIComponent (obj[p])); }                returnStr.join ("&");            }; $httpProvider. defaults.headers.post[' Content-type '] = ' application/x-www-form-urlencoded; Charset=utf-8 ';    }); </script>
Summarize

Angularjs the configuration of the parameters when making the POST request. With regard to the post request of Angularjs, it is recommended to set the request header and request parameter conversion settings for the POST request when initializing the module, which can be easily used elsewhere.

Reference

Http://stackoverflow.com/questions/12190166/angularjs-any-way-for-http-post-to-send-request-parameters-instead-of-json

[Angularjs] $http. Post and $.post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.