简体   繁体   中英

Javascript and Remotipart - Why does single quotes vs double quotes matter?

So, I ran into a really interesting issue when playing around with uploading files remotely with Remotipart . I've tried the following two versions in my update.js.erb view, which the server sends after a successful file upload:

<%= remotipart_response do %>
    $("#container").html('<p>Success!</p><%= link_to('Back', gallery_items_path, :remote => true) %>');
<% end %>

and

<%= remotipart_response do %>
    $("#container").html("<p>Success!</p><%= link_to('Back', gallery_items_path, :remote => true) %>");
<% end %>

Version one successfully changes the markup in #container , and version two fails without any error, server- or client-side. I thought single vs double quotes is only an issue when JSON is in play, but it seems I was wrong. I also noticed the Remotipart example uses single quotes exclusively, and I'm not sure if this is on purpose or not.

I'm using Rails 3.2.1, Remotipart 1.0.2, and (not sure if this matters) Chrome 17.

Does anyone know what causes this?

EDIT: In answer to Alex's question:

In the first case, the output rendered is, as expected:

<div id="container">
    <p>Success!</p>
    <a href="/gallery_items" data-remote="true">Back</a>
</div>

In the second case, like I said, there was no change in the contents of <div id="container"> .

link_to生成带有双引号的链接标记,并在您的JavaScript中关闭引号

The actual js passed to the browser in the 2nd case is;

$("#container").html("<p>Success!</p><a href="/gallery_items" data-remote="true">Back</a>");

The outer string is enclosed in " as its delimiter but as the contents also contain " it breaks. ( x = "aa"bb" is invalid).

The former example uses the ' delimiter so there is no problem.

To use " you must escape link_to 's return to produce

$("#container").html("<p>Success!</p><a href=\"/gallery_items\" data-remote=\"true\">Back</a>");

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