don'除非调用,否则不要在erb中运行JS

don't run JS in erb unless called

本文关键字:erb JS 运行 调用 don      更新时间:2023-09-26

我有一个页面,其中包含一个到ruby函数的ajax GET。Get请求应该返回变量@player。当ajax"成功"时,它应该调用函数popPools

$.ajax({
  type: "GET",
  data: { faceid : response.id },
  url: "/pool/mMypools2",
  success: popPools()
  })

function popPools(){
  $("<%= content_tag(:p, @player[0].id) %>"
  ).appendTo(document.getElementById("asd"));}

我的问题是,在ajax有机会从mMypools响应中获取新变量之前,函数popPools被自动调用。

error:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

因为onload@player不包含任何内容。

感谢

删除popPools:末尾的括号

$.ajax({
  type: "GET",
  data: { faceid : response.id },
  url: "/pool/mMypools2",
  success: popPools
  })

您传递的是popPools函数的结果作为success的值,而不是函数本身。

听起来您在响应模板中做得太多了。Ajax代码实际上属于控制器级别,因为它试图从应用程序中获取数据。模板应该保持"哑"状态,只响应传递给它的变量

为了解决这个问题,我会将文件的顶部完全移出响应模板。一旦你在控制器级别正确加载了@player,然后继续你的响应。哦,别忘了用Javascript转义生成的HTML,或者content_tag函数返回的任何引号都会破坏jQuery。

file.js.erb:

$(
  "<%= j content_tag(:p, @player[0].id) %>"
 ).appendTo(document.getElementById("asd"));}

我希望这个建议能有所帮助。