简体   繁体   中英

Run javascript code after ajax load in div

My ajax code is running very well but i want add javascript in my request file.

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.

Note : I need to write javascript code in code.php.

For some reason I need to run javascript in the code.php

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. If it's not running, I'd check to make sure that the returned HTML is not somehow corrupted. You can use your browser debugging tools to inspect the return body from the ajax call.

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:

<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>
<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

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

test.php

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

maybe that helps?

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