简体   繁体   English

用javascript回复HTML请求?

[英]Respond with javascript to an HTML request?

Is it possible to respond to an HTML request with javascript? 是否可以使用javascript响应HTML请求? By this I mean that I don't want the page to be refreshed and plus execute some javascript code. 我这意味着我不希望刷新页面并加上执行一些javascript代码。 I wonder if this is possible by changing only the server side? 我想知道这是否可以通过仅更改服务器端?

In my action, I have something selected to respond to js and html like this: 在我的行动中,我有一些选择来响应jshtml像这样:

respond_to do |format|
  format.js
  format.html
end

And I have a .js.erb file that, of course, should be rendered when the browser requests a javascript. 我有一个.js.erb文件,当然,应该在浏览器请求javascript时呈现。

Can this be done? 可以这样做吗? How? 怎么样?

You cannot do this by only changing the server side code. 仅通过更改服务器端代码不能这样做。 If you'd like javascript to be executed upon the server's response, then the form will need to be submitted through javascript. 如果你想在服务器的响应中执行javascript,那么表单将需要通过javascript提交。 This is because javascript will eval the response from the server and run the code. 这是因为javascript将评估来自服务器的响应并运行代码。

This can somewhat be trivially added in Rails: 在Rails中可以稍微添加一些:

<%= form_for @user, remote: true %>

When it is submitted, then you can send back javascript. 提交后,您可以发回javascript。 For example, to alert that a user was added: 例如,要提醒用户已添加:

/app/views/users/create.js.erb /app/views/users/create.js.erb

alert("user <%= j @user.email %> was added");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM