Rails 6,如何使用 fetch() 和 params 渲染 .js.erb

问题描述 投票:0回答:1

我正在更新使用 jquery 和 $ajax() 的旧 Rails 应用程序,更新后仍然有效。我想用 .js.erb 和 params 更改 fetch() 的 ajax 调用,一切看起来都很好,但 html 不会被 workbar_work 部分替换。有什么建议吗?

在控制器中:

def switch_state
  permitted_params = params.permit(:partial)
  @partial = permitted_params[:partial].to_s
  @exercise = current_exercise  # defined somewhere else
  respond_to do |format|
     format.js
  end
end

在 switch_state.js.erb 中

$('#workbar_switch').html("<%= j render(partial: @partial, :locals => {exercise: @exercise@}) %>");

获取调用

function switchState(partial, exercise){
  const params = new URLSearchParams();
  params.append('partial', partial);

  fetch("/work/switch_state", {
    method: 'POST',
    headers: {
        'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript',
        'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: params
  })
  .then(response =>  {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.text()
  })  
  .then(responseText => {
    console.log("received js", responseText)
  })
  .catch(error => {
    console.log('Update failed', error)
    console.log('error', error.message)
  })
  .finally(() => {
  })
}

rails 服务器日志 - 看起来不错:

Started POST "/work/switch_state" for ::1 at 2024-12-07 11:19:49 +0100
Processing by WorkController#switch_state as JS
  Parameters: {"partial"=>"workbar_work"}
  Exercise Load (0.3ms)  SELECT "exercises".* FROM "exercises" WHERE "exercises"."unit" = $1 LIMIT $2  [["unit", "ct100_1_ma3"], ["LIMIT", 1]]
  ↳ app/models/exercise.rb:81:in `find_exercise'
  CACHE Exercise Load (0.0ms)  SELECT "exercises".* FROM "exercises" WHERE "exercises"."unit" = $1 LIMIT $2  [["unit", "ct100_1_ma3"], ["LIMIT", 1]]
  ↳ app/models/exercise.rb:81:in `find_exercise'
  Rendering work/switch_state.js.erb
  Rendered work/_workbar_work.html.erb (Duration: 0.6ms | Allocations: 351)
  CACHE Exercise Load (0.0ms)  SELECT "exercises".* FROM "exercises" WHERE "exercises"."unit" = $1 LIMIT $2  [["unit", "ct100_1_ma3"], ["LIMIT", 1]]
  ↳ app/models/exercise.rb:81:in `find_exercise'
  Rendered work/switch_state.js.erb (Duration: 3.4ms | Allocations: 2535)
Completed 200 OK in 17ms (Views: 5.4ms | ActiveRecord: 2.1ms | Allocations: 9998)

浏览器控制台:

  [Log] response – Response {type: "basic", url: "http://localhost:3000/work/switch_state", redirected: false, …} (ctrl-dc34a42ad73de8380cf755f815535ed1b8bfc04007d2b4f4fad4a1f130e93d45.js, line 183)
  [Log] received js – "$('#workbar_switch').html(\"<ul>\\n\t\\n\t<a title=\\\"Klicke hier für eine leichte Übung\\\" id=\\\"bug_click\\\" href=\\\"\\\">\\n\t<l…" (ctrl-dc34a42ad73de8380cf755f815535ed1b8bfc04007d2b4f4fad4a1f130e93d45.js, line 190)
  "$('#workbar_switch').html(\"<ul>\\n  \\n <a title=\\\"Klicke hier für eine leichte Übung\\\" id=\\\"bug_click\\\" href=\\\"\\\">\\n  <li id=\\\"workbar_bug\\\">\\n      <i class=\\\"fa fa-bug\\\"><\\/i>\\n        <span id=\\\"bug_text\\\"><\\/span>\\n  <\\/li>\\n<\\/a>    <a title=\\\"andere Stufe\\\" id=\\\"back_to_base_click\\\" href=\\\"\\\">\\n   <li id=\\\"change_level\\\">\\n     <i class=\\\"fa fa-signal\\\"><\\/i>\\n     <span>andere Stufe<\\/span>\\n  <\\/li>\\n<\\/a>    \\n<\\/ul>\\n\\n<form id=\\\"answerForm\\\"\\n        name=\\\"answerForm\\\"\\n      action=\\\"#dummy\\\">\\n\\n  <div id= \\\"answer_field\\\"\\n              title= \\\"Tippe Deine Antwort hier\\\">\\n         <input type = \\\"text\\\"\\n                     id = \\\"txtanswer\\\"\\n                   name = \\\"txtanswer\\\"\\n                     size = \\\"3\\\"\\n                     maxlength = \\\"3\\\" />\\n              <\\/div>\\n  \\n  <button type=\\\"submit\\\" \\n          id=\\\"submit_answer\\\">\\n    <i class=\\\"fa fa-level-down fa-rotate-90\\\"><\\/i>\\n    <span>OK<\\/span>\\n  <\\/button>\\n\\n<\\/form>\\n\\n\");"
ruby-on-rails parameters fetch
1个回答
0
投票

我明白了

@partial = "workbar_work"
。当
render (partial: workbar_work, ...)
没有找到时,
_workbar_work.html.erb
文件。因为它在工作文件夹内

$('#workbar_switch').html("<%= j render(partial: "work/#{@partial}", :locals => {练习:@exercise@}) %>");

可以设置

@partial = "work/#{permitted_params[:partial].to_s}"

$('#workbar_switch').html("<%= j render(partial: @partial, :locals => {练习:@exercise@}) %>");

© www.soinside.com 2019 - 2024. All rights reserved.