In everyday business, we tend to use Ajax to submit page data without using the form's action to submit the entire form. Now let me share some of the problems I have encountered in my daily work.
One, $.post, $.get, $.ajax three differences:
As the name implies, $.post and $.get send requests to the server using post and get methods respectively. The difference is that the GET request parameter is in the URL directly in the form of url?name1=value1&name2=value2, and the parameters of the POST request will be sent to the server in the form of the request body, this learning javaweb knowledge should know , and do not dwell on it here.
The main point here is about the same asynchronous sending request. $.post and $.get, by default, send requests to the server asynchronously, but in many cases we need to get the return value of the server to determine the next operation, this time need to use the $.ajax.
var flag=false;$.ajax ({ type: "Get", URL: "xxxxxx", async:false, data: {username:name, password:pwd }, DataType: "JSON", success:function (data) { if (data>0) { flag=true; } } );
As in the above code, type to set the request mode,Async is set to synchronous or asynchronous , the default is true asynchronously, at this time set to false. If you use the usual $.post and $.get, the value of flag is not changed with the value of the return value data.
Second, file upload
Ajax uploading files has always been a headache problem, here I use a jquery extension framework, Jquery.form.js, this package provides a $ajaxsubmit method, very good solution springmvc file upload problem, of course, The form form has a method of Post,type of Multipart/form-data and the sample code is as follows:
$ (#id). Ajaxsubmit ({ ' post ', ' xxxxxx ', data: { uername:name, content: Content }, function(data) { /// callback function } });
At this point, the form data and file data are saved in the request to the server. The background fetch code is as follows:
Mutliparthttpservletrequest multipart =(mutliparthttpservletrequest) request; // Convert request to upload file dedicated request map<string,string[]> DataMap = request.getparametermap (); // get the <name,value> key pairs of the ordinary table singular map<string,multipart> Filemap = request.getfilemap (); // gets the key value pair of the uploaded file , which is present in Datamap instead of Fiemap when the file is not uploaded
For the time being so many, I remember to add.
Several scenarios of Ajax submission forms based on SPRINGMVC and jquery