In-depth understanding of $ http. post and $. post, angularjshttp. post in Angularjs

Source: Internet
Author: User

In-depth understanding of $ http. post and $. post, angularjshttp. post in Angularjs

Summary

Angularjs is indeed confused when sending a post request. When transmitting json data, it will always encounter a situation where parameters cannot be accepted on the server side. It is necessary to match $. post.

Example

Here, we simulate a login scenario where the post user name and password are used. The server accepts the account and returns it directly to the client without any other service processing.

Use angularjs

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

Server

  public class AccountController : Controller  {    // GET: /<controller>/    public IActionResult Login()    {      return View();    }    [HttpPost]        public IActionResult Login(string userName,string userPwd)    {      var resut = Request.Form;      return Json(new { _code = 200, _msg = "Login success", name = userName, password = userPwd });    }  }

$. Post

First, use $. post to directly submit the account password.

  $.post("@Url.Content("~/Account/Login")",{ userName: "2342342", userPwd:"2sssdfs" },function (data) {      console.log(data);    });

Response

Let's take a look at the request body.

Now let's take a look at angularjs's $ http. post. What is the difference?

@ {Layout = null ;}<! DOCTYPE html> 

Login

This occurs because $ http. post is usually written in this way. But the result is not desired. Then let's compare the Request body with $. post.

See? The difference is here.

If a problem is found, we need to convert it to the $. post Method for submitting parameters. Fortunately, $ http. post in angularjs provides a transformRequest Method for converting parameters. You can add this parameter 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("&");          }        };

It is used to convert the submitted parameter to the $. post parameter submission method. In this way, the parameters in the Request body are the same as those in $. post.

Global settings are supported.

  <script>    angular.module("login", []).controller("LoginController", function ($http, $scope) {      $scope.Login = function () {        var data = { 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) {        var str = [];        for (var p in obj) {          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));        }        return str.join("&");      };      $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';    });  </script>

Summary

Angularjs requires parameter configuration when making a post request. For angularjs post requests, it is recommended that you set the request header and request parameter conversion settings for post requests during the initialization module, so that they can be conveniently used elsewhere.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.