Difference between Angular and jQuery ajax requests, angularjqueryajax

Source: Internet
Author: User

Difference between Angular and jQuery ajax requests, angularjqueryajax
Recently, angular was used in the project and it was found that parameters could not be obtained in the backend. Therefore, we studied the differences between the two when sending ajax. Note that angular and jquery have different ajax requests. In jquery, the official documentation explains that the default contentType 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, use this content type. default is "application/x-www-form-urlencoded; charset = UTF-8", which is fine for most cases. if you explain itly pass in a content-type$.ajax(), Then it is always sent to the server (even if no data is sent ). the W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. note: For cross-domain requests, setting the content type to anything otherapplication/x-www-form-urlencoded,multipart/form-data, Ortext/plainWill trigger the browser to send a preflight OPTIONS request to the server.

The parameter data and jquery are converted.
  • DataType: PlainObject or String or ArrayData to be 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. seeprocessDataOption to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value oftraditionalSetting (described below ).

See the following section.
Sending Data to the Server

By default, Ajax requests are sent using the get http method. If the POST method is required, the method can be specified by setting a value fortypeOption. This option affects how the contents ofdataOption are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

ThedataOption can contain either a query string of the formkey1=value1&key2=value2, Or an object of the form{key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string usingjQuery.param()Before it is sent. This processing can be circumvented by settingprocessDataTofalse. The processing might be undesirable if you want to send an XML object to the server; in this case, changecontentTypeOption fromapplication/x-www-form-urlencodedTo a more appropriate MIME type.


Therefore, jquery is a javascript Object that converts strings and transmits them to the background. In SpringMVC, you can use the @ RequestParam annotation or request. getParameter () method to obtain parameters.
In angular, the default value of $ http contentType is application/json; charset = UTF-8 in the background, SpringMVC through @ RequestParam annotation or request. getParameter () method is unable to get the parameter.
I wrote a demo program. Html page
123456789101112131415161718192021222324252627282930 <!DOCTYPE html><html><head>    <title></title>    <script src="js/jquery.js"></script>    <script src="js/angular.js"></script> </head><body ng-app="myApp"><div>    <h1>Hello World</h1></div><div>    <span>Angular ajax:</span>    <a href="#" ng-controller="btnCtrl" ng-click="asave()">Button</a></div> <div>    <span>jQuery ajax:</span>    <a href="#" id="jBtn">Button</a></div> <div>    <span>Angular as jQuery ajax:</span>    <a href="#" 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 is to use angular's $ http to send ajax requests. The second is to use jquery's $ ajax to send ajax requests. The third is to use angular's $ http Method to send ajax requests in jquery's way.
12345678910111213141516171819202122232425262728293031323334353637383940414243 var myApp = angular.module('myApp',[]);var btnCtrl = myApp.controller('btnCtrl',['$scope','$http',function($scope,$http){    $scope.asave = function(){        var user = {            name : 'zhangsan',            id : '3'        }        $http({method:'POST',url:'/asave',data:user}).success(function(data){            console.log(data);        })     };    $scope.ajsave = function(){        var data = '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 to see:

When you use jquery to send a request (jsave method), use firbug to see:

Therefore, if you want to use angular to achieve the same effect, it is mainly a bit: 1. modify Content-Type to application/x-www-form-urlencoded; charset = UTF-82. the format of the request parameter is key = value. If there are multiple parameters, use & connect
Ajsave method, after transformation, use firbug to view the source code

This is the frontend sending. How can this problem be solved if springmvc is used to accept parameters? Previously, jquery was used. Generally, the @ RequestParam annotation or request. getParameter method was used to receive data. However, angular cannot accept data. If you want to accept it, you can define an acceptable class. The setter and getter methods are required. Define User class
1234567891011121314151617181920 public class User {    public String name;    public String id;     public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }     public String getId() {        return id;    }     public void setId(String id) {        this.id = id;    }}
In Controller
1234567 @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 defines a class for passing parameters in this request by default. Therefore, when sending a request using angular, you can change it to jquery according to the method described above, it is easier to obtain some simple parameters. Complete controller code:
12345678910111213141516171819202122232425262728293031323334 @Controllerpublic class MyController {     @RequestMapping("/test")    @ResponseBody    public String test(){        return "hello world";    }     @RequestMapping("/asave")    @ResponseBody    public String asave(@RequestBody User user){        System.out.println("name---"+user.getName());        System.out.println("id---"+user.getId());        return "ok";    }     @RequestMapping("/jsave")    @ResponseBody    public String jsave(@RequestParam String name, @RequestParam String id){        System.out.println("name---"+name);        System.out.println("id---"+id);        return "ok";    }     @RequestMapping("/ajsave")    @ResponseBody    public String ajsave(@RequestParam String name, @RequestParam String id){        System.out.println("name---"+name);        System.out.println("id---"+id);        return "ok";    } }





What is the difference between jquery $ ajax $ get $ post?

Load remote data using HTTP requests.

JQuery underlying AJAX implementation. For easy-to-use high-level implementation, see $. get, $. post, and so on. $. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly operate on this function unless you need to operate on uncommon options for more flexibility.

In the simplest case, $. ajax () can be directly used without any parameters.

Note that all options can be set globally using the $. ajaxSetup () function.
Check the API ~!

What is the difference between ajax in jquery and normal AJAX?

Jquery encapsulates native js
When writing normally, you need to write a lot of code to determine which browser is used to correctly use different ajax versions.
$. Ajax $. get $. post and even JSONP have been encapsulated, so you don't need to write a lot of judgment or write native js ajax code. You can call it directly.

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.