jquery load() 去除脚本标签 - 解决方法?

发布于 2024-11-08 16:50:24 字数 3471 浏览 0 评论 0 原文

有谁知道 jquery .load() 的解决方法,去掉从外部内容加载的脚本标签?

有很多文档证明这种情况发生,但在网上搜索了大约 4 个小时后我找不到解决方法?

我正在加载动态生成的 div - 类似于搜索结果页面 - 并且需要将 .click() 绑定到每个动态生成的 div 中的元素。我有一个 php 文件,它执行 html 生成工作并将所有 html 作为字符串返回,但是我无法绑定 jquery .click(),因为包含 jquery 函数的脚本标记被删除。

这是通过调用 php 文件加载外部内容的代码...

$("#titles_wrap").load("m_scripts/m_php/titles_loader.php", function(){
                                                                $..some code
                                                                });

这是生成 div 的 php 文件中的循环(这工作正常)...

$tag1='<script type="text/javascript">';
$tag2='</script>';

while($result_array = mysql_fetch_array($result)) {

            if($i2<=($titles_total)){

                $_SESSION['titles_string'] .= '<li id="listItem_'.$i2.'">

                                                <div id="titles_list_item">

                                                    <div id="titles_list_image_box" style="background-image: url(../../images/thumbs_test/'.$result_array[0].'); background-repeat: no-repeat; ">'.($i2+1).'</div>
                                                    <div id="title_php_loader"></div>
                                                        <div id="title_info_wrap">

                                                        <div id="title_current"><span class="title_current_grey" >current title: </span><br>'.$result_array[1].'
                                                            </div>

                                                                <div id="title_form_wrap">
                                                                    <span class="title_current_grey" >new title: </span><br><input name="title_input_'.$i2.'" id="title_input_'.$i2.'" type="text" class="title_input"></input>
                                                                    <div id="title_send" class="title_send_'.$i2.'">GO</div>
                                                                </div>

                                                            </div>


                                                    '.$tag1.'
                                                    $(".title_send_'.$i2.'").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")})
                                                    '.$tag2.'

                                                </div>
                                            </li>';
                $i2++;
                                }
            }

抱歉,如果第二个代码块有点“过分”侧面 - 让我知道简化的摘录是否更有用。也就是说,您可以在 php 代码最后一行的第 8 行看到 jquery 函数,该函数应该使用动态分配的选择器写入每个 div 中。

当然,代码中可能还有其他错误,但是我无法测试它,直到我可以得到 .load() 来停止破坏它!

如果有人找到了解决这个问题的方法 - 或者甚至是有限恩典的解决方法 - 太棒了!

预先感谢,

干杯,

斯科特

编辑 - 编辑 - 编辑 - 编辑 - 编辑 - 编辑 - 编辑 - 编辑

@TJ Crowder @Frug

感谢您的帮助!

我刚刚仔细查看了您的演示中涉及的页面,是的,我看到您已经可以正常工作了。看起来很神奇,因为它们就在那里 - 那些脚本标签,而且有很多人无法让它工作 - 不幸的是我就是其中之一!

我在您的演示和我的代码情况之间看到的唯一区别是

1)开始脚本标记中没有类型声明,

2)您正在加载带有脚本标记作为 DOM 一部分的页面,而我正在加载 php 字符串输出(我真的不认为这很重要,是吗?当它到达客户端时,一切都会发生相同的事情,不是吗?)

3),您的 .load 调用正在获取整个页面,而我的仅返回元素。我已经更改了输出字符串以包含所有 , 和 标签,但是 grrrrrrr...我仍然无法让该死的脚本标签显示在 DOM 中。

有什么建议吗?有一些我不知道的负载,所以可能是任何东西!谢谢

Does anyone know of a work around for jquery .load() stripping out the script tags loaded from external content?

There's a lot of documentation of the fact that this happens but after something like 4 hours searching the net I can't find a work around?

I'm loading dynamically generated divs - similar to a page of search results - and need to bind a .click() to an element within each dynamically generated div. I've a php file that does the html generation work and returns all the html as a string however I can't bind the jquery .click() as the script tags containing the jquery function get stripped out.

here's the code that loads the external content by calling the php file...

$("#titles_wrap").load("m_scripts/m_php/titles_loader.php", function(){
                                                                $..some code
                                                                });

and here's the loop from the php file that generates the divs (this works fine)...

$tag1='<script type="text/javascript">';
$tag2='</script>';

while($result_array = mysql_fetch_array($result)) {

            if($i2<=($titles_total)){

                $_SESSION['titles_string'] .= '<li id="listItem_'.$i2.'">

                                                <div id="titles_list_item">

                                                    <div id="titles_list_image_box" style="background-image: url(../../images/thumbs_test/'.$result_array[0].'); background-repeat: no-repeat; ">'.($i2+1).'</div>
                                                    <div id="title_php_loader"></div>
                                                        <div id="title_info_wrap">

                                                        <div id="title_current"><span class="title_current_grey" >current title: </span><br>'.$result_array[1].'
                                                            </div>

                                                                <div id="title_form_wrap">
                                                                    <span class="title_current_grey" >new title: </span><br><input name="title_input_'.$i2.'" id="title_input_'.$i2.'" type="text" class="title_input"></input>
                                                                    <div id="title_send" class="title_send_'.$i2.'">GO</div>
                                                                </div>

                                                            </div>


                                                    '.$tag1.'
                                                    $(".title_send_'.$i2.'").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")})
                                                    '.$tag2.'

                                                </div>
                                            </li>';
                $i2++;
                                }
            }

Sorry if this second code block is a bit on the 'overkill' side - let me know if a simplified excerpt would be more useful. That said, you can see on the 8th from last line of the php code the jquery function that should get written into each div with a dynamically assigned selector.

Of course, it could be that there's other errors in the code however I'm not going to be able to test it until I can get .load() to stop trashing it!

If anyone's found a solution to this - or even a workaround of limited grace - brilliant!

Thanks in advance,

Cheers,

Scott

EDIT - EDIT - EDIT - EDIT - EDIT - EDIT - EDIT - EDIT

@T.J. Crowder
@Frug

Thanks for your help!

I've just had a good hard look at the pages involved in your demo and yes, I see you've got it working. Seems amazing cos there they are - those script tags and there are SO many people out there who can't get it to work - unfortunately I'm one of them!

The only differences I see between your demo and my code situation was

1) no type declaration in the opening script tag,

2) you're loading a page with script tags as part of the DOM, whereas I was loading php string output (I really don't think this matters tho', eh? By the time it hits the client it all comes to the same thing, no?)

3), your .load call was fetching a whole page whereas mine was returning only elements. I've since changed the output string to include all , and tags but grrrrrr...I still can't get dem damn script tags to show up in the DOM.

Any suggestions? There's loads I don't know about so could be anything! thanks S

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

苏别ゝ 2024-11-15 16:50:24

立即更新,您可以在 jQuery 文档网站上找到:

http://api.jquery.com/load/

确实如此仅当使用特定后缀选择器调用 load 时,才会删除标签。

脚本执行

当使用不带后缀选择器表达式的 URL 调用 .load() 时,内容会在删除脚本之前传递到 .html()。这会在脚本块被丢弃之前执行它们。但是,如果使用附加到 URL 的选择器表达式来调用 .load(),则脚本会在更新 DOM 之前被删除,因此不会执行。这两种情况的示例如下所示:

此处,作为文档一部分加载到 #a 中的任何 JavaScript 都将成功执行。
1

$('#a').load('article.html');

但是,在以下情况下,加载到 #b 的文档中的脚本块将被剥离并且不会执行:
1

$('#b').load('article.html #target');

Update now, which you can find on the jQuery doc site:

http://api.jquery.com/load/

It DOES strip tags only if you call load with a specific suffixed selector..

Script Execution

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

Here, any JavaScript loaded into #a as a part of the document will successfully execute.
1

$('#a').load('article.html');

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:
1

$('#b').load('article.html #target');
你的心境我的脸 2024-11-15 16:50:24

该线程现在有点旧了,但我找到了我想分享的 $.load + 选择器 +

$.ajax({
    url: '/some/url',
    success: function(html) {
        var content = $('<div />').html(html).find('#my-custom-selector');
        $('#container-to-place-html-in').html(content);
    }
});

干杯,Alex

This thread is a bit older now, but I found a workaround for the $.load + selector + <script> issue/feature which I would like to share. Maybe it will be helpful to someone. Instead of $.load, I use this:

$.ajax({
    url: '/some/url',
    success: function(html) {
        var content = $('<div />').html(html).find('#my-custom-selector');
        $('#container-to-place-html-in').html(content);
    }
});

Cheers, Alex

怀念你的温柔 2024-11-15 16:50:24

jQuery load 不会 去掉脚本标签 (示例),并且从 PHP 脚本返回的内容中没有脚本标记。有一些 JavaScript,但它没有正确嵌入 script 标记中,因此浏览器无法识别它。

如果您希望 this: 中的 JavaScript

...
'.$tag1.'
$(".title_send_'.$i2.'").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")})
'.$tag2.'
...

被识别为 JavaScript,请将其放在 script 标记中。

...
'.$tag1.'
<script>"$(".title_send_'.$i2.'").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")})</script>
'.$tag2.'
...

...或者更好的是,在内容末尾使用单个 script 标记来连接事物,或者使用 加载函数。


更新:重新编辑:

1)开始脚本标记中没有类型声明,

没关系,请参阅这个更新的示例。浏览器根据始终应用的相同规则解释 script 标记。

2) 你正在加载一个带有脚本标签作为 DOM 一部分的页面,而我正在加载 php 字符串输出(我真的不认为这很重要,是吗?当它到达客户端时,一切都发生了都是同样的事情,不是吗?)

是的,一旦到达浏览器,一切都会发生同样的事情。

3),您的 .load 调用正在获取整个页面,而我的仅返回元素。我已经更改了输出字符串以包含所有 , 和 标签,但是 grrrrrrr...我仍然无法让这些该死的脚本标签显示在 DOM 中。

我的示例只是加载一个片段,而不是整个页面。

我不知道为什么你的不起作用。我想知道它是否与循环输出的多个脚本元素有关,或者与您连接 click 处理程序的事实有关,但是 这两者都不是

没有什么可以做的,只能拿你的非工作示例并一点一点地剥离层,直到找到当你删除它时让它开始工作的部分。从根本上讲,使用 load 并不是使脚本无法工作(无论你发现有多少人认为是这种情况;世界很大,有很多人)几乎任何事情都思考的人)。您必须放弃这样的想法:这与 jQuery 的 load 函数对脚本执行任何操作有关;可能不是。

调试此类事情的关键实际上是简化、简化、简化。确保服务器为 ajax 调用返回的 HTML 看起来像您想象的那样(没有奇怪的引号或其他东西)。尝试用静态页面来做。 ETC。

jQuery load doesn't strip out script tags (example), and there are no script tags in the content you're returning from your PHP script. There is some JavaScript, but it's not correctly embedded in script tags and so it's not being recognized by the browser.

If you want the JavaScript in this:

...
'.$tag1.'
$(".title_send_'.$i2.'").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")})
'.$tag2.'
...

to be recognized as JavaScript, put it in a script tag.

...
'.$tag1.'
<script>"$(".title_send_'.$i2.'").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")})</script>
'.$tag2.'
...

...or better yet, use a single script tag at the end of the content to hook things up, or the callback on the load function.


Update: Re your edit:

1) no type declaration in the opening script tag,

Doesn't matter, see this updated example. The browser interprets the script tag according to the same rules it always applies.

2) you're loading a page with script tags as part of the DOM, whereas I was loading php string output (I really don't think this matters tho', eh? By the time it hits the client it all comes to the same thing, no?)

Right, it all comes to the same thing once it gets to the browser.

3), your .load call was fetching a whole page whereas mine was returning only elements. I've since changed the output string to include all , and tags but grrrrrr...I still can't get dem damn script tags to show up in the DOM.

My example is just loading a snippet, not a full page.

I don't know why yours isn't working. I wondered if it related to multiple script elements being output in a loop, or the fact you were hooking up a click handler, but it's not either of those.

There's nothing for it but to take your non-working example and peel layers away bit by bit until you find the part that, when you remove it, lets it start working. Fundamentally, again, it's not that using load makes the scripts not work (regardless of how many people you find who think that's the case; it's a big world, there are lots of people who think nearly anything). You have to let go of the idea that this is related to jQuery's load function doing anything to the scripts; it probably isn't.

The key to debugging this kind of thing really is simplify, simplify, simplify. make sure the HTML being returned by the server for the ajax calls looks the way you think it does (no weird quotes or something). Try to do it with static pages. Etc.

昨迟人 2024-11-15 16:50:24

您能否确认是否正在删除脚本或事件绑定不起作用?
不过,我认为你可以稍微改变一下方法。
首先修改你的脚本

$("#titles_wrap").load("m_scripts/m_php/titles_loader.php", function(){
                                                                $..some code
                                                                $("[class^='title_send_']").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")});
                                                                });

,然后从 php 代码中删除脚本部分

while($result_array = mysql_fetch_array($result)) {

            if($i2<=($titles_total)){

                $_SESSION['titles_string'] .= '<li id="listItem_'.$i2.'">

                                                <div id="titles_list_item">

                                                    <div id="titles_list_image_box" style="background-image: url(../../images/thumbs_test/'.$result_array[0].'); background-repeat: no-repeat; ">'.($i2+1).'</div>
                                                    <div id="title_php_loader"></div>
                                                        <div id="title_info_wrap">

                                                        <div id="title_current"><span class="title_current_grey" >current title: </span><br>'.$result_array[1].'
                                                            </div>

                                                                <div id="title_form_wrap">
                                                                    <span class="title_current_grey" >new title: </span><br><input name="title_input_'.$i2.'" id="title_input_'.$i2.'" type="text" class="title_input"></input>
                                                                    <div id="title_send" class="title_send_'.$i2.'">GO</div>
                                                                </div>

                                                            </div>
                                                </div>
                                            </li>';
                $i2++;
                                }
            }

Can you please confirm if it is stripping out the scripts or the event bind isn't working?
However, I think you can change the approach a little bit.
First modify your script like

$("#titles_wrap").load("m_scripts/m_php/titles_loader.php", function(){
                                                                $..some code
                                                                $("[class^='title_send_']").click(function(){$("#title_php_loader").load("m_scripts/m_php/title_sender.php")});
                                                                });

Then remove the script part from php code

while($result_array = mysql_fetch_array($result)) {

            if($i2<=($titles_total)){

                $_SESSION['titles_string'] .= '<li id="listItem_'.$i2.'">

                                                <div id="titles_list_item">

                                                    <div id="titles_list_image_box" style="background-image: url(../../images/thumbs_test/'.$result_array[0].'); background-repeat: no-repeat; ">'.($i2+1).'</div>
                                                    <div id="title_php_loader"></div>
                                                        <div id="title_info_wrap">

                                                        <div id="title_current"><span class="title_current_grey" >current title: </span><br>'.$result_array[1].'
                                                            </div>

                                                                <div id="title_form_wrap">
                                                                    <span class="title_current_grey" >new title: </span><br><input name="title_input_'.$i2.'" id="title_input_'.$i2.'" type="text" class="title_input"></input>
                                                                    <div id="title_send" class="title_send_'.$i2.'">GO</div>
                                                                </div>

                                                            </div>
                                                </div>
                                            </li>';
                $i2++;
                                }
            }
月隐月明月朦胧 2024-11-15 16:50:24

为什么不能使用回调函数来绑定事件而不是将其内联到 php 页面上?

可能有一种方法可以解决这个问题,但我一开始就不会内联它,这就是为什么你没有发现其他人这样做的原因。如果您将绑定放入回调中,它们将在加载时附加。

Why can't you use the callback function to bind the events rather than inlining it on your php page?

There might be a way to work around that but I wouldn't inline it in the first place which is why you're not finding others doing it. If you put binds in the callback they will attach when it's loaded.

初懵 2024-11-15 16:50:24

我知道这很糟糕,但你可以做的一件事就是在正在加载的 html 中编写类似的内容,然后在回调中的 .ajax 或 .load 方法之后执行字符串替换 -> html = html.replace( /lscript/g, '脚本' );

为此,应该将标签拉为未执行的标签。

希望有帮助:)

It sucks I know but one thing you can do is write something like within the html being loaded then after you .ajax or .load method in the callback do a string replace -> html = html.replace( /lscript/g, 'script' );

something to that effect should pulled the tag as an un-excuted tag.

hope that helps :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文