Ajax request differences between angular and JQ

Source: Internet
Author: User

Using angular in recent projects, the results found that the background was unable to get parameters, so a little bit of the difference between the two when sending Ajax. Note that the Ajax requests for angular and jquery are different. In jquery, the official document explains ContentType default is application/x-www-form-urlencoded; Charset=utf-8
  • ContentType (default: ‘application/x-www-form-urlencoded; charset=UTF-8‘ ) Type:stringwhen sending data to the server with this content Type. Default is "application/x-www-form-urlencoded; Charset=utf-8 ", which is fine for the most cases. If you explicitly pass in a content-type $.ajax() to, then it's always sent to the server (even if no data is sent). The XMLHttpRequest specification dictates, the CharSet is always UTF-8; Specifying another charset the encoding of the browser to change. Note:for Cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded , multipart/form-data , or would text/plain trigger the B Rowser to send a preflight OPTIONS request to the server.
The parameter data,jquery is converted.
  • Datatype:plainobject or String or arraydata to is sent to the server. It is converted to a query string, if not already a string. It ' s appended to the URL for get-requests. See processData option to prevent this automatic processing. Object must be key/value pairs. If value is a Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described B Elow).
Look at the following paragraph.
Sending Data to the Server

By default, Ajax requests is sent using the GET HTTP method. If the POST method is required, the method can being specified by setting a value for the  type  option. This option affects how the contents of the  data  option is sent to the server. POST data would always be transmitted to the server using UTF-8 charset, per the the website XMLHttpRequest standard.

datathe option can contain either a query string key1=value1&key2=value2 of the form, or an object of the form {key1: ‘value1‘, key2: ‘value2‘} . If The latter form is used, the data is converted to a query string using jQuery.param() before it is sent. This processing can is circumvented by setting processData to false . The processing might is undesirable if you wish to send a XML object to the server; In this case, change the contentType option from to application/x-www-form-urlencoded a more appropriate MIME type.

So, jquery is a JavaScript object that converts strings to the background. In Springmvc, you can use the @requestparam annotation or the Request.getparameter () method to get the parameters. In angular, the default value of the $http contenttype is application/json;charset=utf-8 in the background, Springmvc the @requestparam annotation or Request.getparameter () method is not available for parameters. Wrote the demo program. HTML page
123456789101112131415161718192021222324252627282930 <!DOCTYPE html><html><head>    <title></title>    <scriptsrc="js/jquery.js"></script>    <script src="js/angular.js"></script></head><bodyng-app="myApp"><div>    <h1>Hello World</h1></div><div>    <span>Angular ajax:</span>    <ahref="#"ng-controller="btnCtrl"ng-click="asave()">Button</a></div><div>    <span>jQuery ajax:</span>    <ahref="#"id="jBtn">Button</a></div><div>    <span>Angular as jQuery ajax:</span>    <ahref="#"ng-controller="btnCtrl"ng-click="ajsave()">Button</a></div></body><script src="js/index.js"></script></html>
There are three buttons on the page: the first to send AJAX requests using the angular $http the second $ajax to send AJAX requests using jquery, and the third to use the $http method of angular to send AJAX requests in a jquery way
12345678910111213141516171819202122232425262728293031323334353637383940414243 varmyApp = angular.module(‘myApp‘,[]);varbtnCtrl = myApp.controller(‘btnCtrl‘,[‘$scope‘,‘$http‘,function($scope,$http){    $scope.asave = function(){        varuser = {            name : ‘zhangsan‘,            id : ‘3‘        }        $http({method:‘POST‘,url:‘/asave‘,data:user}).success(function(data){            console.log(data);        })    };    $scope.ajsave = function(){        vardata = ‘namelisi&id=4‘         $http({            method: ‘POST‘,            url: ‘ajsave‘,            data: data,  // pass in data as strings            headers: {‘Content-Type‘‘application/x-www-form-urlencoded; charset=UTF-8‘}          }).success(function(data) {                console.log(data);         });    };}]);$(‘#jBtn‘).on(‘click‘,function(){    $.ajax({        type : ‘POST‘,        url : ‘jsave‘,        data : {name:‘wangwu‘,id:‘5‘},        dataType:‘json‘,        success : function(data){            console.log(data);        }    })});
When sending a request using angular (Asave method), use Firbug: When sending a request using jquery (Jsave method), use Firbug to see: So, if you want to use angular to achieve the same effect, Mainly a bit: 1. Modify Content-type to application/x-www-form-urlencoded; charset=utf-82. The format of the request parameter format Key=value, if, many, then uses the & connection Ajsave method, after the transformation, uses the Firbug to see the source code this is the front end sends, that backend uses the SPRINGMVC to accept the parameter, how to deal with? Previously, jquery was used, generally using @requestparam annotations or Request.getparameter methods to accept data. However, after using angular, this does not accept data. If you want to accept it, you can define an accepted class with a setter and getter method. Defining the User Class
1234567891011121314151617181920 publicclassUser {    publicString name;    publicString id;    publicString getName() {        returnname;    }    publicvoid setName(String name) {        this.name = name;    }    publicString getId() {        returnid;    }    publicvoidsetId(String id) {        this.id = id;    }}
In the controller
1234567 /td> @RequestMapping ( "/asave" )       @ResponseBody      public   String asave ( @RequestBody   user user) {           System.out.println ( "Name---" +user.getname ());          System.out.println ( "id---" +user.getid ());          return   "OK" ;      }
Therefore, angular the default method of this request, but also to define a class, so, in the use of angular to send the request, you can follow the above methods to change to jquery mode, so that for some simple parameters, access is more convenient. Full controller code:
12345678910111213141516171819202122232425262728293031323334 @ControllerpublicclassMyController {    @RequestMapping("/test")    @ResponseBody    publicString test(){        return "hello world";    }    @RequestMapping("/asave")    @ResponseBody    publicString asave(@RequestBodyUser user){        System.out.println("name---"+user.getName());        System.out.println("id---"+user.getId());        return"ok";    }    @RequestMapping("/jsave")    @ResponseBody    publicString jsave(@RequestParamString name, @RequestParam String id){        System.out.println("name---"+name);        System.out.println("id---"+id);        return"ok";    }    @RequestMapping("/ajsave")    @ResponseBody    publicString ajsave(@RequestParamString name, @RequestParamString id){        System.out.println("name---"+name);        System.out.println("id---"+id);        return"ok";    } }

Ajax request differences between angular and JQ

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.