Method _ AngularJS

Source: Internet
Author: User
This article shares with you the $ http. post () when submitting data, the backend cannot receive the parameter value problem. If you are interested, refer to the background for writing this article: Learn How to Use angular's $ http. when the post () API submits data, the backend cannot receive the parameter value. Therefore, it looks for relevant information and finds a solution.

The purpose of this article is to summarize the following findings based on the solution and experience in the above article.
Front-end: html, jquery, angular
Backend: java and springmvc
I. post submission and receipt Methods
The front end uses jquery to submit data.


$.ajax({  url:'/carlt/loginForm',  method: 'POST',    data:{"name":"jquery","password":"pwd"},  dataType:'json',  success:function(data){    //...  }});


Backend java receiving:


@ Controllerpublic class UserController {@ ResponseBody @ RequestMapping (value = "/loginForm", method = RequestMethod. POST) public User loginPost (User user User) {System. out. println ("username:" + user. getName (); System. out. println ("password:" + user. getPassword (); return user ;}} model (do not forget the get and set methods): public class User {private String name; private String password; private int age; // setter getter method}


Background printing:

Username: jquery
Password: pwd

The frontend returned results returned by calling the interface:

Ii. Use angularJs's post Method for submission


Js Code:

var app = angular.module('myApp', []);app.controller('formCtrl', function($scope,$http) { $scope.login = function() {  $http({   url:'/carlt/loginForm',   method: 'POST',      data: {name:'angular',password:'333',age:1}    }).success(function(){   console.log("success!");  }).error(function(){   console.log("error");  }) };});


Background print result:

Username: null
Password: null:

View the frontend:

3. Solve the angular post submission problem.
I believe that even people who have read the article mentioned above already know how to solve the problem. In this article, angular's submission method is changed, making angular's data submission method more like jquery's.

I tried it. It works. Then I tried another method. As follows:

The front-end remains unchanged:


var app = angular.module('myApp', []);app.controller('formCtrl', function($scope,$http) {  $scope.login = function() {    $http({      url:'/carlt/loginForm',      method: 'POST',            data: {name:'angular',password:'333',age:1}       }).success(function(){      console.log("success!");    }).error(function(){      console.log("error");    })  };});


The background changes, but @ RequstBody is added before the User, because angular submits a json object:


@Controllerpublic class UserController {  @ResponseBody  @RequestMapping(value="/loginForm",method=RequestMethod.POST)  public User loginPost(@RequestBody User user){    System.out.println("username:"+user.getName());    System.out.println("password:"+user.getPassword());    return user;  }}@RequestBody


Purpose:

(I) This annotation is used to read part of the body data of the Request. It is parsed using HttpMessageConverter, Which is configured by default by the system, and then the corresponding data is bound to the object to be returned;

Ii) then, bind the object data returned by HttpMessageConverter to the parameters of the method in the controller.

Time to use:

A) when the GET and POST methods are submitted, the request header Content-Type value is used to determine whether:

Application/x-www-form-urlencoded, optional (that is, not required, because the data in this case @ RequestParam, @ ModelAttribute can also be processed, of course @ RequestBody can also be processed );
Multipart/form-data cannot be processed (that is, @ RequestBody cannot be used to process data in this format );
Other formats are required (other formats include application/json and application/xml. Data in these formats must be processed using @ RequestBody );
B) When submitting in PUT modeRequest header Content-TypeTo determine:

Application/x-www-form-urlencoded, required;
Multipart/form-data cannot be processed;
Other formats, required;
Note: The data encoding format of the request body is specified by the Content-Type of the header;

4. After angular is solved, it is found that jquery will report an error (error code 415) when submitting a post request in the original method ).

The following method solves the jquery submission problem:


$.ajax({  url:'/carlt/loginForm',  method: 'POST',  contentType:'application/json;charset=UTF-8',  data:JSON.stringify({"name":"jquery","password":"pwd"}),  dataType:'json',  success:function(data){    //...  }});


Json object to json string: JSON. stringify (jsonObj );

The above is the solution to the problem that angular's $ http. post () does not receive the parameter value when submitting data _ AngularJS content in the background. For more information, see the PHP Chinese Network (www.php1.cn )!

Related Article

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.