简体   繁体   English

从JavaScript调用Rails操作

[英]call rails action from javascript

I have a scenario where I need to show the preview of form in a new window. 我有一种情况,需要在新窗口中显示表单的预览。

I am stuck on how to invoke the rails action preview from javascript function and how to launch a new window for that action. 我被困在如何从javascript函数调用rails动作预览以及如何为该动作启动新窗口的问题。

Here's the code: 这是代码:

click preview link code:

<%= link_to_function "#{image_tag('preview.png', :alt=>'Preview', :title=>'See a preview')}
<span class='text'>Preview</span>",
 "javascript:show_form()" %>

javascript function:

function show_form() {
    //grab the dom
      var html = $('#newform').clone();
    //whats next here?????
}

 rails action:

 def preview
    @html = params[:html]
 end

My question is: 我的问题是:

  • How do I call the rails action preview? 如何调用Rails动作预览?
  • how do I launch a new window with the preview for that action? 如何启动带有该操作预览的新窗口?

thanks for your help 谢谢你的帮助

Edit:

I am able to post data using $.post('/url') from jquery. 我能够使用jquery中的$ .post('/ url')发布数据。 However, the view is not being rendered. 但是,该视图未呈现。 I can see that the view is being called(debug hits the breakpoint) but the browser does not render it. 我可以看到该视图正在被调用(调试命中断点),但浏览器未呈现它。 Is there anything I need to do in the .post() method to route to the new url? 我需要在.post()方法中进行任何操作以路由到新网址吗?

Since you're using jQuery, you might as well use its AJAX libraries: http://api.jquery.com/category/ajax/ 由于您使用的是jQuery,因此不妨使用其AJAX库: http : //api.jquery.com/category/ajax/

In most cases, using $.get() or $.post() is sufficient. 在大多数情况下,使用$.get()$.post()就足够了。 You can use $.ajax() for more flexibility, at the cost of having to type out more options. 您可以使用$.ajax()获得更大的灵活性,但必须输入更多选项。

Basically your goal is to call the URL that maps to the appropriate controller action. 基本上,您的目标是调用映射到适当控制器操作的URL。 That action should return a view with the appropriate HTML, XML, or JSON. 该操作应返回带有适当的HTML,XML或JSON的视图。 If it just returns the HTML for the form, you can use jQuery on the result to get the appropriate values and do what you need to do with them. 如果它只是返回表单的HTML,则可以在结果上使用jQuery以获取适当的值并执行所需的操作。

EDIT: 编辑:

The AJAX calls take a success callback function that you can provide to actually render the form. AJAX调用采用了成功回调函数,您可以提供该函数以实际呈现表单。

Example: 例:

$.post('/url', function (data) {
    $('#myForm').html(data); // this would simply inject the returned HTML into the form
});

EDIT (again): 编辑(再次):

Just reread your question. 只需重新阅读您的问题即可。 Seems you're trying to render everything in a new window? 似乎您要在新窗口中渲染所有内容? Assuming your view renders an entire block of HTML (with DOCTYPE and <html> ), you can use window.open and just specify the URL. 假设您的视图呈现HTML的整个块(使用DOCTYPE和<html> ),则可以使用window.open并仅指定URL。 You don't need AJAX at all in that case. 在这种情况下,您根本不需要AJAX。

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

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