简体   繁体   中英

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.

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?
  • 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. 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?

Since you're using jQuery, you might as well use its AJAX libraries: http://api.jquery.com/category/ajax/

In most cases, using $.get() or $.post() is sufficient. You can use $.ajax() for more flexibility, at the cost of having to type out more options.

Basically your goal is to call the URL that maps to the appropriate controller action. That action should return a view with the appropriate HTML, XML, or 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.

The AJAX calls take a success callback function that you can provide to actually render the form.

Example:

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

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. You don't need AJAX at all in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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