简体   繁体   English

为什么HTTP删除需要javascript才能起作用?

[英]Why does HTTP delete need javascript to work?

I was working with Devise in Rails and while setting up the sign_out function I run into errors. 我在Devise in Rails中工作,并且在设置sign_out函数时遇到错误。 I noticed than, it happened because pages which have sign_out link skipped layouts so Javascript was inactive. 我注意到,这是因为具有sign_out链接的页面跳过了布局,因此Javascript处于非活动状态。 By enabling javascript with:` 通过启用javascript:

<%= javascript_include_tag :defaults %>

everything just worked fine. 一切都很好。

Why does it work like that? 为什么会这样工作?

links are (normally) always get requests. 链接(通常)总是得到请求。 In order for a link to send a non-get request you need some javascript that modifies the behaviour of the link. 为了使链接发送非获取请求,您需要一些javascript来修改链接的行为。

In addition browsers typically only support GET/POST requests so rails fakes up the other methods (DELETE, PUT,...) by adding a _method field to the post. 另外,浏览器通常仅支持GET / POST请求,因此Rails通过在帖子中添加_method字段来伪造其他方法(DELETE,PUT等)。

Here's excerpt from jquery_ujs.js . 这是jquery_ujs.js的摘录。 It'll shed some light on how it is done: 它将阐明如何完成:

// Handles "data-method" on links such as:
// <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
handleMethod: function(link) {
  var href = link.attr('href'),
    method = link.data('method'),
    target = link.attr('target'),
    csrf_token = $('meta[name=csrf-token]').attr('content'),
    csrf_param = $('meta[name=csrf-param]').attr('content'),
    form = $('<form method="post" action="' + href + '"></form>'),
    metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';

  if (csrf_param !== undefined && csrf_token !== undefined) {
    metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
  }

  if (target) { form.attr('target', target); }

  form.hide().append(metadata_input).appendTo('body');
  form.submit();
},

So, by clicking on such a link you're basically trigger sending of a hidden form (that is being created during the click) with some parameters that simulate DELETE HTTP verb. 因此,通过单击这样的链接,基本上可以触发带有一些模拟DELETE HTTP动词的参数的隐藏表单(在单击期间创建的表单)的发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM