不引人注目的 JavaScript 无法在 Rails 3 应用程序中运行
尝试将 mixpanel 的代码添加到我的网站中。但是,当我对表单执行 onsubmit 时,我无法在 Rails 3 应用程序中使用 JavaScript 来跟踪事件。该代码确实可以在 Chrome 的控制台窗口中运行。有什么建议吗?下面是我的 html.erb 文件中的代码。它与 mixpanel 提供的 javascript 一起放置在文件的头部。
<% javascript_tag do %>
var my_term = <%= strip_tags(@term.to_json) %>
<% end %>
这是我在表单中跟踪提交的代码
<%= form_tag("/search", :method => "get", :onsubmit => 'mpq.track("search",{"term":my_term});', :style => "float:right;margin-top:9px;") do %>
感谢
生成的 js
<script type="text/javascript">
//<![CDATA[
var my_term = "san francisco"
//]]>
</script>
生成的 html
<form accept-charset="UTF-8" action="/search" method="get" onsubmit="mpq.track("search",{"term":my_term});" style="float:right;margin-top:9px;">
Attempting to add mixpanel's code into my site. However, I cannot get the javascript in my rails 3 app to track an event when I do an onsubmit for the form. The code does work from the console window of chrome. Any suggestions? Below is the code from my html.erb file. This is placed in the head of the file, along with the provided javascript from mixpanel.
<% javascript_tag do %>
var my_term = <%= strip_tags(@term.to_json) %>
<% end %>
Here's the code that I have in my form to track a submit
<%= form_tag("/search", :method => "get", :onsubmit => 'mpq.track("search",{"term":my_term});', :style => "float:right;margin-top:9px;") do %>
Thanks
Generated js
<script type="text/javascript">
//<![CDATA[
var my_term = "san francisco"
//]]>
</script>
Generated html
<form accept-charset="UTF-8" action="/search" method="get" onsubmit="mpq.track("search",{"term":my_term});" style="float:right;margin-top:9px;">
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码有两个问题:
1 - 查看生成的 HTML 中的 onsubmit:
当您应该使用实际的
"
时,您正在使用"
2 -在某些情况下,即使修复了“问题”,该事件也不会触发,这是因为在调用 Mixpanel 有机会解决之前页面会发生变化。在搜索页面本身上,而不是使用onsubmit javascript 事件。
There are two issues with your code:
1 - Look at your onsubmit in your generated HTML:
You are using
"
when you should be using an actual"
2 - In some cases, even after fixing the " issue, the event will not fire. This is because the page will change before the call to Mixpanel has a chance to resolve. It would be better just to call mpq.track() on the search page itself, instead of using an onsubmit javascript event.