¿Cómo enviar una solicitud PUT / DELETE en jQuery?


GET:$.get(..)

POST:$.post()..

¿Qué pasa con PUT/DELETE?

Author: Damjan Pavlica, 2010-01-28

12 answers

Puedes usar el método ajax :

$.ajax({
    url: '/script.cgi',
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
});
 814
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-28 10:58:15

$.ajax funcionará.

$.ajax({
   url: 'script.php',
   type: 'PUT',
   success: function(response) {
     //...
   }
});
 108
Author: Jacob Relkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-04 09:35:18

Podemos extender jQuery para hacer accesos directos para PUT y DELETE:

jQuery.each( [ "put", "delete" ], function( i, method ) {
  jQuery[ method ] = function( url, data, callback, type ) {
    if ( jQuery.isFunction( data ) ) {
      type = type || callback;
      callback = data;
      data = undefined;
    }

    return jQuery.ajax({
      url: url,
      type: method,
      dataType: type,
      data: data,
      success: callback
    });
  };
});

Y ahora puedes usar:

$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
   console.log(result);
})

Copia de aquí

 67
Author: Stepan Suvorov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-01 13:03:44

Parece ser posible con Función ajax de jQuery especificando

type: "put" o type: "delete"

Y no es compatible con todos los navegadores, pero la mayoría de ellos.

Echa un vistazo a esta pregunta para obtener más información sobre la compatibilidad:

¿Los métodos PUT, DELETE, HEAD, etc. están disponibles en la mayoría de los navegadores web?

 28
Author: Pekka 웃,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:26

Desde aquí , puedes hacer esto:

/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

Es básicamente una copia de $.post() con el parámetro method adaptado.

 9
Author: user2503775,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-28 09:18:31

Debería ser capaz de utilizar jQuery.ajax :

Cargar una página remota usando un HTTP solicitud.


Y puede especificar qué método debe usarse, con el type opción :

El tipo de solicitud a realizar ("POST" o "GET"), el valor predeterminado es " GET".
Nota: Otros Métodos de solicitud HTTP, como PUT y DELETE, también se puede utilizar aquí, pero no son compatibles con todos navegador.

 5
Author: Pascal MARTIN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-28 10:59:05

Ajax()

Busca param type

Otros métodos de solicitud HTTP, como PUT y DELETE, también se pueden usar aquí, pero no son compatibles con todos los navegadores.

 4
Author: antpaw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-28 10:58:40

Aquí está una llamada actualizada ajax para cuando está utilizando JSON con jQuery > 1.9:

$.ajax({
    url: '/v1/object/3.json',
    method: 'DELETE',
    contentType: 'application/json',
    success: function(result) {
        // handle success
    },
    error: function(request,msg,error) {
        // handle failure
    }
});
 4
Author: moodboom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-05 17:40:16

¡Puedes hacerlo con AJAX !

Para PUT método :

$.ajax({
  url: 'path.php',
  type: 'PUT',
  success: function(data) {
    //play with data
  }
});

Para DELETE método :

$.ajax({
  url: 'path.php',
  type: 'DELETE',
  success: function(data) {
    //play with data
  }
});
 3
Author: Xanarus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-17 04:27:35

Por brevedad:

$.delete = function(url, data, callback, type){

  if ( $.isFunction(data) ){
    type = type || callback,
    callback = data,
    data = {}
  }

  return $.ajax({
    url: url,
    type: 'DELETE',
    success: callback,
    data: data,
    contentType: type
  });
}
 2
Author: Paul Wand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-04 09:49:45

He escrito un plugin de jQuery que incorpora las soluciones discutidas aquí con soporte entre navegadores:

Https://github.com/adjohnson916/jquery-methodOverride

¡Échale un vistazo!

 1
Author: AndersDJohnson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-06 19:41:44

Podría incluir en su hash de datos una clave llamada: _method con el valor 'delete'.

Por ejemplo:

data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
  alert('Yupi Yei. Your product has been deleted')
});

Esto también se aplicará a

 0
Author: mumoc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-12 22:36:26