简体   繁体   English

在 div 中加载 ajax 后运行 javascript 代码

[英]Run javascript code after ajax load in div

My ajax code is running very well but i want add javascript in my request file.我的 ajax 代码运行良好,但我想在我的请求文件中添加 javascript。

My code is:我的代码是:

$('#result').load('code.php');

This runs well but in code.php i put this code <script>alert('hi');</script> it does not give an error message or the alert.这运行良好,但在code.php我把这段代码<script>alert('hi');</script>它没有给出错误消息或警报。

Note : I need to write javascript code in code.php.注意:我需要在 code.php 中编写 javascript 代码。

For some reason I need to run javascript in the code.php出于某种原因,我需要在code.php运行 javascript

Can any body help me?有谁能够帮助我?

Try:尝试:

$('#result').load('code.php', function() { alert("hi!"); });

Now, the thing is that an inline <script> block in the HTML returned from your PHP code should run.现在,事情是从 PHP 代码返回的 HTML 中的内联<script>应该运行。 If it's not running, I'd check to make sure that the returned HTML is not somehow corrupted.如果它没有运行,我会检查以确保返回的 HTML 没有以某种方式损坏。 You can use your browser debugging tools to inspect the return body from the ajax call.您可以使用浏览器调试工具检查 ajax 调用的返回正文。

I don't relay know why it doesn't work for you but if it doesn't have a look at my answer我不知道为什么它对你不起作用,但如果它没有看看我的答案

I think this should work:我认为这应该有效:

$("body").load("code.php", function(data) {
    data
        .replace(/\r|\n|\t/g, "")
        .replace(
            /<script.*?>.*?<\/script>/gi, 
            function(input) {
                $("script:first").prepend(input);
            }
        );
});

If not try this:如果没有试试这个:

$("body").load("code.php", function(data) {
    data = data
        .replace(/\r|\n|\t/g, "")
        .replace(
            /<script(\s.*?(src="(.*?)".*?)?)?>(.*?)<\/script>/gi, 
            function(input, match1, match2, match3, match4, match5) {
                if (match3) {
                    $("script:first").prepend(input);
                } else if (match5) {
                    eval(match5);
                }
            }
        );
});

try this as script in your php:试试这个作为你的 php 中的脚本:

<script type="text/javascript" language="javascript">alert('hi');</script>

set type and language设置类型和语言

edit:编辑:

my files我的文件

my setup of files was like this我的文件设置是这样的

test.html测试.html

<html>
<header>
<title>test</title>
<script type='text/javascript' src='jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='test.js'></script>
</header>
<body>
<div id="result">adasd</div>
</body>
</html>

test.js测试.js

$(document).ready(function(){
     $("#result").load("test.php");
});

test.php测试文件

<script type="text/javascript" language="javascript">alert('hi');</script>
<?php
    echo 'test';
?>

maybe that helps?也许这有帮助?

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

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