JQuery用DELETE method發送Ajax request

Knowledge point:

$.post( url [, data ] [, success ] [, dataType ] ) 

is a shorthand Ajax function, which is equivalent to:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});


Two approaches:

1. a form with a hidden field ‘_method’ set to ‘delete’ and use JQuery $.post method:

1.1 form code:

<form action="test url" accept-charset="UTF-8" method="post" class="form_example">
  <input type="hidden" name="_method" value="delete" />
  <label for="Please_enter_the_username_that_you_want_to_delete:">Please enter the username that you want to delete:</label>
  <input type="text" name="name" id="name" />
  <input type="submit" name="commit" value="Send delete request" />
</form>


1.2 JQuery code:

$(‘.form_example’).submit(function(e) {
  var $this = $(this);
  var form = $this;
  var data = form.serialize();

  // Prevent form form submit normally
  e.preventDefault();

  // Use ajax to submit the form
  $.post(form.attr(‘action’), data).done(function(data) {
  // If ajax request succeed, code goes here
  });
});

2. a form without ‘_method’ hidden field and use JQuery $.ajax method with ‘type’ set to ‘delete':

2.1 form code:

<form action=”test url” accept-charset=”UTF-8″ method=”post” class=”form_example”>
  <label for=”Please_enter_the_username_that_you_want_to_delete:”>Please enter the username that you want to delete:  </label> 
  <input type=”text” name=”name” id=”name” /> 
  <input type=”submit” name=”commit” value=”Send delete request” />
</form>

2.2 JQuery code:

$(‘.form_example’).submit(function(e) {
  var $this = $(this);
  var form = $this;
  var data = form.serialize();

  // Prevent form form submit normally
  e.preventDefault();

  // Use ajax to submit the form
  $.ajax({
    type: ‘delete’,
    url: form.attr(‘action’),
    data: data,
    success: //code goes here,
    dataType: //code goes here
  });
});




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章