简体   繁体   中英

on button click add action url jquery

I have a link like this:

<a class="glyphicon glyphicon-remove glyphicon-color-red btn-delete" data-toggle="modal" data-target="#myModal" user-id="56f52ea551d72027711157d6"></a>

And with jquery, on click I take parameter user-id and I change action URL, this code isn't working cause when I click the delete button modal popup appears, but if I do inspect element I see that action is empty?

$('.btn-delete').click(function () {
  var user_id = $(this).attr('user-id');
  $('#modal-form').attr('action', "{{ url_for('admin.delete_user', id=" +user_id+" ) }}");
    });

The method that I use in route admin.delete_user in python is:

def delete_user(self, id):
    mongo.db.users.remove({'_id': ObjectId(id)})
    return redirect(url_for('admin.users'))

And the modal popup:

<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></h4>
    </div>
    <form id="modal-form" action=" "  method="POST">
    <div class="modal-body">
      <p>Are you sure?</p>
    </div>
    <div class="modal-footer">
          <button type="button" class="btn btn-default btn-sm btn-style" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-default btn-sm btn-filter-apply btn-style" >Yes</button>
    </div>
    </form>
  </div>
</div>

I don't understand why in jquery the action URL is not added?

在进行任何更改之前,请确保已加载DOM,可以使用ready()进行更改:

$(document).ready(function(){ /* your code */ });

I would change your url_for function to to produce part of the url you need, then place it in the action attr. Then, use jquery to append the user_id to the string. Make sure you modify whatever is grabbing the url to parse a parameter. Here's an example:

url_for returns something like: http://www.example.com?delete_user=

Then your form action:

<form id="modal-form" action="{{url_for(delete_user)}}"  method="POST">

And your jquery would then:

$('.btn-delete').click(function () {
    var user_id = $(this).attr('user-id');
    var action = $('#modal-form').attr('action');
    $('#modal-form').attr('action', action + user_id);
});

Finally, whatever is parsing your form would look for the url parameter delete_user= and use the user_id you appended to it.

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