Maison  >  Questions et réponses  >  le corps du texte

javascript - AJAX如何实现PUT和DELETE方法

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

PHP中文网PHP中文网2749 Il y a quelques jours623

répondre à tous(6)je répondrai

  • 迷茫

    迷茫2017-04-10 15:00:29

    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

    répondre
    0
  • ringa_lee

    ringa_lee2017-04-10 15:00:29

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

    目前我在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

    répondre
    0
  • 迷茫

    迷茫2017-04-10 15:00:29

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

    répondre
    0
  • 天蓬老师

    天蓬老师2017-04-10 15:00:29

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

    répondre
    0
  • 天蓬老师

    天蓬老师2017-04-10 15:00:29

    $.ajax({
      url: "http://localhost:10320/api/Person/4",
      type: "POST",
      data: JSON.stringify(whatever),
      headers: { 
          "Content-Type": "application/json",
          "X-HTTP-Method-Override": "PUT" }, //PUT,DELETE
    })
    

    répondre
    0
  • 黄舟

    黄舟2017-04-10 15:00:29

    DELETE和PUT需要apache nginx配置实现支持才行的需要web容器的支持,和其他无关的.

    répondre
    0
  • Annulerrépondre