Home > Article > Web Front-end > Detailed explanation of the method of using ajax to pass arrays and receive in the background
This article mainly introduces to you the relevant information about using ajax to transfer arrays and receive in the background. The introduction in the article is very detailed and has certain reference and learning value for everyone. Friends who need it can come and learn together.
Preface
We are using ajax to asynchronously submit the multi-select box to get the ID of the object that needs to be operated. At this time, we can put each Make an object with the id, then put it into an array, and then use JSON.stringify()
to format the array as json; parse our json string in the inputStream in the background, and then Just use:
new JSONArray()
Get the json array, and loop to parse the attributes we want:
var countsCheckBox = $("input[type='checkbox']:checked"); var booksid = []; for(var i=0;i<countsCheckBox.length;i++){ //使用[]取得元素是是一个domElement元素,取值需要使用.value, //如果使用countsCheckBox.eq(i) 则是一个Obkject元素,就可以使用val()取值 //alert(countsCheckBox[i].value); mysendbook_id = {}; mysendbook_id['book_id'] = countsCheckBox[i].value; booksid[i] = mysendbook_id; } //alert(booksid); var confirmdel= confirm('确认要删除吗?'); if(confirmdel){ //开始请求删除 $.ajax({ url:'selectdelbooks', data:JSON.stringify(booksid), type:'post', success:function(res){ alert("删除成功"); location.replace("/TheDemo/books/pageBooksShow"); } }); }
In the above js, we put each selected id into the "book_id" attribute of mysendbook_id, and then put this object into the booksid array; use
# when sending an asynchronous request ##JSON.stringify(bookid)Format this booksid array and get a json array.
Let’s look at how we receive it in the background:
@RequestBody. But this is more troublesome;
IOUtils.toString to convert the inputStream to a string, and then use
new JSONArray( mybooksid);Get this json array
<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>This way We get a list with the id value we selected. Information in the database:
How to solve the problem of Ajax passing data with special characters
Configuring Chrome to support local (file protocol) AJAX request (graphic tutorial)
Simple implementation of AJAX paging effect (graphic tutorial)
The above is the detailed content of Detailed explanation of the method of using ajax to pass arrays and receive in the background. For more information, please follow other related articles on the PHP Chinese website!