简体   繁体   中英

AJAX request only functioning properly when all the code is on one line

I have an AJAX request that gets sent from a controller like so:

in controller:

  respond_to do |format|
    format.js {render 'show_data'}
  end

show_data.js.erb

$('#foo').html("<%= render partial: "foo/show_data" %>");

In partial: _show_data.html.erb

<table> <tr> <th><%= "Name" %> </th> <th><%= "ID" %> </th> </tr> <tr> <td> <%= "Steve" %> </td> <td> <%= "1"%> </td> </tr> </table>

The above table only gets rendered appropriately when all the code is on one line. If i press the return key it doesn't show up inside the target div after the AJAX request has gone through. This is not unique to the table tag I've just used it as an example. Anytime there's more than one line it doesn't show up.

Response when it works:

$('#proto').html("<table> <tr> <th>Name </th> <th>ID </th> </tr> <tr> <td> Steve </td> <td> 1  </td> </tr> </table>");

Response when it doesn't work:

$('#proto').html("<table> <tr> <th>Name </th> <th>Rep ID </th> </tr> <tr> <td> @rep.name </td> <td> @rep.id  </td> </tr> </table>
");

This same system of making AJAX requests works fine in another app of mine. Any help would be greatly appreciated, thanks a lot!

Is it so important to have the string in few lines instead of a single, long line? If so, use something like:

$('#proto').html(
       "<table> <tr> <th>Name </th>"
     + "<th>ID </th> </tr>"
     + "<tr> <td> Steve </td>"
     + "<td> 1  </td> </tr> </table>"
);

The above table only gets rendered appropriately when all the code is on one line. If i press the return key it doesn't show up inside the target div after the AJAX request has gone through.

That's because JS doesn't allow text literals to go over multiple lines. (And you should have gotten a corresponding error message in your error console.)

You can work around that in several ways:

  • Concatenate several one-line literals with + as Kamil already suggested.
  • Terminate every line with a \\ character (that way JS allows a text literal to continue on the next line).
  • Probably easiest if you don't need line breaks in your code output for readability (but still need the line breaks in the value): Replace line breaks in your text with \\n (the actual two characters \\ and n ), so that JS sees something like "Foo\\nBar". That will still mean a line break in the actual value, but it does not break JS syntax.
  • Remove line breaks altogether (and replace them with a space) if you don't need line breaks in the actual value.

All of those could be done server-side automatically.

Turns out I forgot to include 'escape_javascript' before 'render'. I'm about to go drown myself in the shower. Thank you for the answers.

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