Detailed explanation of the method for passing arrays and receiving in the background using ajax, ajax Array
Preface
We can obtain the id of the object to be operated in the Multi-selection box submitted asynchronously using ajax. In this case, we can create an object for each id, put it in an array, and then useJSON.stringify()
Format the array in json format. parse our json string in inputStream in the background and then use:
new JSONArray()
Get the json array and parse the expected attributes cyclically:
Var countsCheckBox = $ ("input [type = 'checkbox']: checked"); var booksid = []; for (var I = 0; I <countsCheckBox. length; I ++) {// use [] to obtain an element is a domElement element. The value must be used. value, // If countsCheckBox is used. eq (I) is an Obkject element, you can use val () value // alert (countsCheckBox [I]. value); mysendbook_id ={}; mysendbook_id ['book _ id'] = countsCheckBox [I]. value; booksid [I] = mysendbook_id;} // alert (booksid); var confirmdel = confirm ('Are you sure you want to delete it? '); If (confirmdel) {// starts to request deletion $. ajax ({url: 'selectdelreads', data: JSON. stringify (booksid), type: 'post', success: function (res) {alert ("deleted successfully"); location. replace ("/TheDemo/books/pageBooksShow ");}});}
In js above, we put each selected id in the "book_id" attribute of mysendbook_id, and then put this object in the array of booksid; used to send asynchronous requests
JSON.stringify(bookid)
Format the booksid array to obtain a json array.
Let's look at how we receive it in the background:
One is to create a list in a class. This list contains only one class with the bookid attribute, and then uses annotations.@RequestBody
Add the parameter. However, this is troublesome;
Another method is to obtain data from the input stream.IOUtils.toString
Convert inputStream into a string and then usenew JSONArray(mybooksid);
Obtain the json array.
In this way, the attribute value of book_id in each json file is obtained.
<span style="font-family:SimSun;font-size: 10.5pt;"> </span><span style="font-family:KaiTi_GB2312;font-size:14px;"> @RequestMapping("selectdelbooks") public String selectdelbooks(HttpServletRequest request) throws Exception { ServletInputStream inputStream = request.getInputStream(); String mybooksid = IOUtils.toString(inputStream); JSONArray jsonarr = new JSONArray(mybooksid); List<String> book_id =new ArrayList<String>(); for (int i=0;i<jsonarr.length();i++){ book_id.add(((JSONObject)jsonarr.get(i)).getString("book_id")); }...</span>
In this way, we get a list with the selected id value.
Database Information:
Multiple choices on the page:
The id of the selected book in the background:
In this way, the collection of IDS is convenient for subsequent operations.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.