SPRINGMVC Learning notes: Ajax interacts with controller's parameters __ajax

Source: Internet
Author: User
Tags string format
key parameter settings in Jquery.ajax (options)

Jquery.ajax (options): Load remote Data via HTTP request. The following parameters (a typical AJAX request code below) need to be paid attention to when interacting with the controller of Jquery.ajax and SPRINGMVC:

$.ajax ({
      type: "POST",
      URL: "$!{ _index}/buauth/save4 ",
      data:JSON.stringify (dataobj),
      contentType:" Application/json; Charset=utf-8 ",
      dataType:" JSON ",
      success:function (response, IFO) {}
});
ContentType
Parameter type: String
Description: (Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. Default values are appropriate for most applications. Tells the server the data format submitted from the browser.
For example, if we use the Json2.js method json.stringify (obj) to format the JSON string when we submit the data, the default submission is an error. This time you need to specify that the submitted content format is: "Application/json". Data
Parameter type: object,string
Description: Data sent to the server. If the data type is a JavaScript object or an array, jquery automatically invokes the Jquery.param () method before committing to encode the data to be sent as "application/x-www-form-urlencoded" (i.e. NAME=VALUE&NAME1=VALUE1), at which time the argument is object and must be in key/value format, and if it is an array, JQuery will automatically correspond to the same name for the different values. such as {foo:["bar1", "Bar2"]} converted to ' &foo=bar1&foo=bar2 ';
If the data data type is of type string, the direct default is that it has been encoded in the "application/x-www-form-urlencoded" format and is no longer converted. DataType
Parameter type: String
Description: The data type expected to be returned by the server. Sets the contents of the "Accept" field in Httpheader, telling the server what type of data format the browser can expect to return, and jquery also processes the returned data based on that type. If not specified, JQuery will automatically return Responsexml or responsetext based on the HTTP packet MIME information and pass as a callback function parameter, available values:
"XML": Returns an XML document that can be processed with jQuery.
HTML: Returns plain text HTML information, including script elements.
Script: Returns the plain text JavaScript code. Results are not automatically cached.
"JSON": Returns JSON data. jquery automatically translates the returned string format data into JavaScript objects, making it easy to access them directly using the Obj.property format. If you do not specify this option, jquery does not automatically convert even if you return a string in JSON format.
"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function.

Reference blog: http://fyq891014.blog.163.com/blog/static/20074019120123305029795/ Controller Accept parameters in normal way pass parameters

@RequestMapping (value = "Buauth/save")
@ResponseBody public
String Save (Integer id) {
    System.out.println (ID);
    return "SUCCESS";
}

The

accepts parameters in this way, and the underlying implementation is similar to the request. GetParameter () Gets the parameter, note: If the address bar/buauth/save the above pass parameter, when the ID is integer, the value is null, Then when the ID is an int type, the error will be.
When the Address bar is/buauth/save?id=10 access mode, the parameter is appended to the URL, at which point there are three ways to receive controller 1.String save (@RequestParam value= UserID ") Integer ID, which assigns the value of the address bar parameter named UserID to the parameter ID, and if the parameter name on the address bar is ID, the
2 is not received. String Save (@RequestParam integer ID), in which case the ID is taken as the parameter name to receive the assignment
3.String Save (integer ID), in which case the ID is also taken as the parameter name to receive the assignment by default
Note: If the argument is preceded by a @requestparam annotation, if the address bar does not have an argument for the annotation, such as an ID, then a 404 error is reported and the path cannot be found.
When using Ajax request methods, you need to set 22 (1) set contenttype parameter value is: application/x-www-form-urlencoded (this is the default value, you can not set) (2) The request parameter data must be a JS object. At this point, the Ajax parameters show that jquery automatically calls the Jquery.param () method to organize the data to be sent into a similar application/x-www-form-urlencoded (i.e. name=value&name1= value1), and then in controller the SPRINGMVC frame automatically injects the corresponding value into the corresponding parameter. An example of an AJAX approach is as follows:

$.ajax ({
    type: "POST",
    URL: "$!{ _index}/buauth/save ",
    data: {buAuth:JSON.stringify (Dataobj), menuids:menu_ids},
    dataType:" JSON ",
    Success:function (data) {}
});
or
$.post ("$!{ _index}/buauth/save ", {buAuth:JSON.stringify (dataobj), menuids:menu_ids},function (result) {});
@RequestMapping (value = "Buauth/save")
@ResponseBody public
string Save (String buauth,string menuids) {
try {
    //need to call the function to convert the string to the corresponding bean
        buauth Buauthbean = Json.parseobject (Buauth, buauth.class);
        System.out.println (Menuids);
    } catch (Exception e) {
        System.out.println (e.getmessage ());
    }
    return "SUCCESS";
}

Note: (1) It is possible to pass multiple objects in this way, to map each object to a JSON string on the front of the controller corresponding method parameters, and then in the function body to resolve each of the different objects to achieve the effect of passing multiple objects.
(2) When the controller method parameter is the entity class, this method can also automatically inject into the entity class of the parameter, at this time the injection process is similar to the model in Struts2, for example as follows:

$.ajax ({
    type: "POST",
    URL: "$!{ _index}/buauth/save2 ",
    data:dataobj,//dataobj must be a JS object, for example: {menutype:" POP ", Busiscope:" 12,11,89 "}
    DataType : "JSON",
    success:function (data) {}
});
@RequestMapping (value = "Buauth/save2")
@ResponseBody public
String save2 (Buauth buauth) {return
    " SUCCESS ";
}
to pass parameters @RequestBody annotations
@RequestMapping (value = "buauth/save1")
@ResponseBody public
String save1 (@RequestBody buauth buauth) { return
    "SUCCESS";
}

Using the @requestbody annotation parameters, the Springmvc frame bottom can automatically complete the JSON string to the corresponding bean and inject into the method parameter, mainly by using the Handleradapter The configured httpmessageconverters resolves the post data body and then binds to the corresponding bean. The data value that Ajax sends must be a JSON string, and if you need to map to a custom bean object in controller, you must set Ajax contenttype to Application/json (or application/ XML). The complete example of this approach is as follows:

$.ajax ({
    type: "POST",
    URL: "$!{ _index}/buauth/save1 ",
    data:JSON.stringify (dataobj),//pass parameter must be a JSON string
    contentType:" Application/json; Charset=utf-8 ",//must declare contenttype as Application/json, otherwise the background using @requestbody annotation cannot parse parameter
    dataType:" JSON ",
    Success:function (response, info) {}
});
@RequestMapping (value = "buauth/save1")
@ResponseBody public
String save1 (@RequestBody buauth buauth) {
    return "SUCCESS";
}

Note: (1) The front end directly with $.post () Direct request will have problems, contenttype default is application/x-www-form-urlencoded. You need to use $.ajaxsetup () to mark the ContentType as Application/json (or application/xml).

$.ajaxsetup ({ContentType: "Application/json"});
$.post ("$!{ _index}/buauth/save ", {buAuth:JSON.stringify (dataobj), menuids:menu_ids},function (result) {});

(2) You can use @responsebody to pass an array, for example (as a direct reference to other blog examples)

var savedataary=[];
var data1={"UserName": "Test", "Address": "GZ"};
var data2={"UserName": "Ququ", "Address": "GR"};
Savedataary.push (data1);
Savedataary.push (data2);
$.ajax ({
    type: "POST",
    URL: "User/saveuser",
    dataType: "JSON",
    contentType: "Application/json",
    data:JSON.stringify (savedata),
    success:function (data) {}
});
@RequestMapping (value = "Saveuser", method = {Requestmethod.post}}) 
@ResponseBody public  
void Saveuser (@ Requestbody list<user> users) { 
    userservice.batchsave (users); 
}

(3) The same method in controller can only use @responsebody to mark one parameter. It means that you cannot pass multiple objects directly through this method, but you can indirectly pass multiple objects by setting an intermediate Pojo object (setting different properties). Examples are as follows:

var buauthpage = {
    Buauth:   data,
    menuinfo: {code: "M"}
;
$.ajax ({
    type: "POST",
    URL: "$!{ _index}/buauth/save5 ",
    data:JSON.stringify (buauthpage),
    contentType:" Application/json; Charset=utf-8 ",
    dataType:" JSON ",
    success:function (data) {
    }
});
public class Buauthpage {
    Buauth buauth;
    Menuinfo Menuinfo;

    Public Buauth Getbuauth () {return
        buauth;
    }
    public void Setbuauth (Buauth buauth) {
        This.buauth = Buauth;
    }
    Public Menuinfo Getmenuinfo () {return
        menuinfo;
    }
    public void Setmenuinfo (Menuinfo menuinfo) {
        this.menuinfo = menuinfo;
    }
}
@RequestMapping (value = "Buauth/save5")
@ResponseBody public
String save5 (@RequestBody buauthpage Buauthpage) {return
    "SUCCESS";
}

Reference Bowen: http://blog.csdn.net/kobejayandy/article/details/12690555
Http://www.cnblogs.com/quanyongan/archive /2013/04/16/3024741.html

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.