简体   繁体   中英

script within a php page not executed when called using ajax

Please read below my scenario… I have a PHP file wherein I have javascript within it..

 <?php
   echo ‘<script>’;
   echo ‘window.alert(“hi”)’;
   echo ‘</script>’;

 ?>

On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed. Can you please let me know the possible reasons. (note: I'm in a compulsion to have script within php page).

When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.

$.get('/alertscript.php', {}, function(results){
    $("html").append(results);
});

Make sure you change the code to fit your needs. I'm supposing you use jQuery...

Edited version

load('/alertscript.php', function(xhr) {    
    var result = xhr.responseText;  

    // Execute the code
    eval( result ); 

});



function load(url, callback) {
    var xhr;

    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0", 
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0", 
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]

        for(var i = 0, len = versions.length; i < len; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        }
            catch(e){}
        } // end for
    }

    xhr.onreadystatechange = ensureReadiness;

    function ensureReadiness() {
        if(xhr.readyState < 4) {
            return;
        }

        if(xhr.status !== 200) {
            return;
        }

        // all is well  
        if(xhr.readyState === 4) {
            callback(xhr);
        }           
    }

    xhr.open('GET', url, true);
    xhr.send('');
}

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