如何将当前用户的 ID 插入 ajax 中的 url 部分?

How do I interpolate the current user's id into the url section in ajax?

我正在尝试替换 getEvents 函数中 url 字段中的“2”,并使其动态化以获取当前用户的 ID。

我想做类似 ${current_user.id} 的事情。我该怎么做?理想情况下,这就是我想要做的:

function getEvents() {
  $.ajax({
    url: 'http://localhost:3000/users/`${current_user.id}`/events',
    method: 'get',
    dataType: 'json'
  }).done(function(data) 

我的 ApplicationController 文件中有一个 current_user 方法。我试过在其上应用 json 但出现错误。 下面是完整的代码。

 class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  helper_method :current_user, :logged_in?, :log_user_in #let these methods be used in views

  private
  def log_user_in
    session[:user_id] = @user.id
  end

  def logged_in?
    !!current_user
  end

  def current_user #should return previous user or look for current user
    @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
  end
end

$(function() {
  console.log('event.js is loaded...')
  listenForClick()
});

function listenForClick() {
  $('button#events-data').on('click', function(event) {
    event.preventDefault()
    getEvents()
  })

  function getEvents() {
  $.ajax({
    url: 'http://localhost:3000/users/2/events',
    method: 'get',
    dataType: 'json'
  }).done(function(data) {

    console.log("the data is: ", data)
    debugger
    let myEvent = new Event(data[0])
    let myEventHtml = myEvent.eventHTML()
    document.getElementById('ajax-events').innerHTML += myEventHTML
  })
}


class Event {
  constructor(obj) {
    this.id = obj.id
    this.name = obj.name
    this.host = obj.host
    this.description = obj.description
    // this.host.user.id = obj.user.id
  }
}


Event.prototype.newEventForm = function() {
   (`
  <strong>New Event</strong>
  <form>
    <input id='event-name' type='text' name='name'></input><br>
    <input type='text' name='description'></input><br>
    <input type='submit'/>
    </form>
  `)
};

在 rails 的视图传递 url 中添加: 添加类似(更改路径以更正):

javascript_tag("window.UPDATE_URL = #{update_user_path(current_user)};")

在 JS 中

  $.ajax({
    url: window.UPDATE_URL,

根据 post 中提到的描述,您可以做的是:

1) 直接访问脚本标签中的变量

var user_id = <% current_user.id %>

2) 将从控制器传递的 id 附加到 html 正文中的元素。

然后从设置它的元素中获取 id 的值。

希望对您有所帮助!!

我明白了。我只需要写: ${this.href} 在 url 部分。