AJAX如何实现PUT和DELETE方法


目前我在jquery里只看到了POST和GET方法,现在很多RESTful接口都有PUT和DELETE接口,但是真正前端却没看到有调用这两种方法的,是浏览器不支持吗?还是什么其它原因?

http jquery Ajax JavaScript

super 9 years, 5 months ago

Jquery里的POST和GET都是对ajax方法的封装,你可以自己进行封装。


 $.ajax({
  url: 'www.website.com',
  type: 'DELETE',
  data: {}
});

执行后就会有 Request Method:DELETE 的http头被传到后端。OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE都是可以使用的Http1.1(连IE7都支持,其他浏览器不可能不支持)。至于你说的实现问题,我认为不存在,只是你服务端有没有做相应的处理,HTTP是协议不是技术。

方法GET和HEAD应该被所有的通用WEB服务器支持,其他所有方法的实现是可选的。

W3C有明确的说明。
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

乃们都是禽兽 answered 9 years, 5 months ago

浏览器暂时不支持,我们的做法是前端加上 _method 参数说明方法,后端也判断一下

这是何等的纠结 answered 9 years, 5 months ago

浏览器暂时不支持。
node中有method override组件,可以去用 get 或者 post 请求模拟 put delete

双子座D叹息 answered 9 years, 5 months ago

其实这个问题挺浪费时间的

目前我在jquery里只看到了POST和GET方法

文档里写的很明白还有个$.ajax方法吧,$.post和$.get方法的文档也声明了他们只是对.ajax的封装,这是基本查文档的能力吧


 $.ajax({
  url: '/test',
  type: 'DELETE',
  data: {}
});

就在这个页面打开console运行上面这段代码,看看发出了什么请求?

真正前端却没看到有调用这两种方法的

基于Restful风格接口的前端框架不要太多,Backbone.js源码够清楚吧

你这个问题的答案,在Backbone.js源码里都有很清楚的交待:

Turn on emulateHTTP to support legacy HTTP servers. Setting this option will fake "PATCH", "PUT" and "DELETE" requests via the _method parameter and set a X-Http-Method-Override header.

链接: http://backbonejs.org/docs/backbone.html#section-14

Turn on Backbone.emulateHTTP in order to send PUT and DELETE requests as POST, with a _method parameter containing the true HTTP method, as well as all requests with the body as application/x-www-form-urlencoded instead of application/json with the model in a param named model. Useful when interfacing with server-side languages like PHP that make it difficult to read the body of PUT requests.

链接: http://backbonejs.org/docs/backbone.html#section-157

代号罪 answered 9 years, 5 months ago

Your Answer