简体   繁体   中英

Javascript post request one key and multiple values

I have a script to submit an array of id's to be deleted. The script is not tied to a form.

The data is in the form of {'id': [1,2]} .

When I run the script, the form data is changed to id[]: 1

I have tried $.param() , but that just creates a single string.

I could join 1,2 into a string (ie {id: "1,2"} , but would prefer to avoid that. Any suggestions?

function delete_messages(event){
   let data = {id: [1,2]};
   event.preventDefault();
   let parameters = {
     url: '/message/delete'
     type: "POST",
     data: data,
     dataType: "html"
   };
   addcsrf();
   $.ajax(parameters).done(function(data){
      alert("successfully deleted");
   })
   .fail(function(data){
      alert("failed to delete");
   });
 } 

Flask Code

@bp.route('/message/delete', methods=['POST'])
@login_required
def message_delete():
    message_ids = request.form.get('msg_id')
    deleted = []
    for id in message_ids:
        msg = RecipientData.query.get(id)
        if msg is not None and msg.user_id == current_user.id:
            msg.update(status='trash')
    return redirect(url_for('main.view_messages', folder="inbox"))
var ids=[];
ids[0] = 1;
ids[1] = 2;

In the ajax request, change the data as given below:

 data: {ids:ids},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM