如何在 Rails 中向需要身份验证的操作发出 AJAX 请求?

发布于 2024-10-27 03:50:48 字数 420 浏览 2 评论 0原文

我正在尝试向 Rails 控制器发送 AJAX 请求,该控制器使用 before_filter 对用户进行身份验证。问题是当请求发送时,即使用户已经登录,服务器也会要求身份验证。

这是我的 AJAX 请求:

$.ajax({
  type: 'DELETE',
  url: "/messages/delete_all",
  data: [1,2,4],
  success: function() {
        console.log("Your request is received.")
    }
});

当用户从浏览器中点击 delete_all 时,它可以工作,但是AJAX 则不然。什么给?

编辑:它可能与authenticity_token相关吗?

I am trying to send an AJAX request to a Rails controller that uses before_filter to authenticate the user. The problem is when the request gets sent, the server asks for authentication even if the user is already logged in.

Here is my AJAX request:

$.ajax({
  type: 'DELETE',
  url: "/messages/delete_all",
  data: [1,2,4],
  success: function() {
        console.log("Your request is received.")
    }
});

When the user hits delete_all from the browser, it works, but with AJAX it doesn't. What gives?

EDIT: could it be related to the authenticity_token?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不回头走下去 2024-11-03 03:50:48

也许这个问题会有所帮助:将 javascript 与 twitter API 结合使用

在您的情况下,那里提出的解决方案应该看起来像这样

$.ajax({    
  type: 'DELETE',
  url: "/messages/delete_all",
  data: [1,2,4],
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authentication", "Basic  " + encodeBase64(username + ":" + password)
  },
  success: function() {
    console.log("Your request is received.")
  }
});

Maybe this question will help: Using javascript with the twitter API

The solution proposed there should look something like this in your case

$.ajax({    
  type: 'DELETE',
  url: "/messages/delete_all",
  data: [1,2,4],
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authentication", "Basic  " + encodeBase64(username + ":" + password)
  },
  success: function() {
    console.log("Your request is received.")
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文