简体   繁体   中英

How to include js file in ajax call?

I am calling a ajax method to update a div. It contains links and functions which require java script files. But these methods and functions are not getting called properly as java script files are not getting included through ajax call. For example, i am trying to call a light box function, but it gets redirected to different page and not in light box.

Thanks in advance, Anubhaw Prakash

The Ajax framework in prototype will properly execute the text content of <script> tags, but will not import new script files via <script src="somefile.js"/> . The only solution I came up with is to import all javascript files I need in the head of the page. That way the functions in the imported file are available to the inline javascript code executed in the Ajax response.

I had a similar problem, where I did want to postload some javascript. What I did is separating loading the html-fragment and loading the script into two calls. For loading the script I call the following function (I have JQuery handling the ajax part):

function loadModule(name, callback) {
    $.ajax({type: "POST"
          , url: "/js/" + name
          , dataType: "script"
          , success: callback
    });     
}

I see you're using Ruby on Rails — does that mean you're using Prototype on the client? If so, Prototype's Ajax.Updater will ignore script tags that reference external files (it will evaluate script tags that have their contents inline). So to add those external files to your page, you'll have to hook into the process via the onSuccess callback, look in the responseText for script tags with src attributes, and handle those yourself. Once you've identified the relevant script tags and extracted their src attributes, you can include them by dynamically adding the scripts as described in this article from the unofficial Prototype & script.aculo.us wiki.

<script> tags written to innerHTML are not executed at write-time. You can do element.getElementsByTagName('script') to try to get hold of them and execute their scripts manually, but it's very ugly and not reliable.

There are tedious browser differences to do with what happens to a <script> element written to innerHTML which is then (directly or via an ancestor) re-inserted into the document. You want to avoid this sort of thing: just don't write <script> ​s to innerHTML at all.

Then you also don't have to worry about executing scripts twice, which is something you never want to do with library scripts. You don't want to end up with two copies of a function/class that look the same but don't compare equal, and which hold hooks onto the page that don't play well with each other. Dynamically-inserted library scripts are a recipe for confusing failure.

Much better to include your scripts statically, and bind them to page elements manually after writing new elements to the page. If you really need to you can have your AJAX calls grab a JSON object containing both the new HTML to add and a stringful of script to execute.

可能想尝试在:before选项中运行一些预备javascript来设置具有正确文件的变量?

hey i found a way to add it....:)

NOTE- this is a synchronous process so you dont have to worry about that the script is loaded or not.... the script will always load the instance u call the function and you can start using the loaded script instantaneously..

lets use these 2 functions

1) first one is the ajax function to retrieve the values where async should be true to send the request synchronously

    // AJAX FUNCTION
    function loadXMLDoc(reqt,url,reqp,cfunc,async)
    {
        var xmlhttp;
        try// code for IE7+, Firefox, Chrome, Opera, Safari
        {
            xmlhttp=new XMLHttpRequest();
        }
        catch(err)// code for IE6, IE5
        {
            try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e){
                try{
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(E){}
            }
        }
        if(!xmlhttp)
        {
            alert("error");
        }
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            cfunc(xmlhttp.responseText);
        }
    }
    if(reqt=='GET')
    {
        url+=(reqp!=""?"?":"")+reqp;
        xmlhttp.open("GET",url,(async?false:true));
        xmlhttp.send();
    }
    else if(reqt=='POST')
    {
        xmlhttp.open("POST",url,(async?false:true));
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(reqp);
    }
    else
    {
        return false;
    }
    }
    /*use this function
    loadXMLDoc(reqt,url,reqp,function(response){
    });
    */

2)then we use ajax to load the js file as string and then append it to the new script tag's innerHTML and then append it to the head section and one more thing to ensure file is already loaded i used the id of script tag as the path to the file which makes it really easy task to check for the duplicate...:)

    //add new script dynamically
    function add_script(src)
    {
        if(!document.getElementById(src))
        {
            loadXMLDoc("GET",src,"",function(jsresp){
                var head = document.getElementsByTagName("head")[0];
                var script=document.createElement("script");
                script.type='text/javascript';
                script.id=src;
                script.text=jsresp;
                head.appendChild(script);
            },true);
        }
    }

thanks for all help i used to get and will get from this site and its users for the development purposes...

regards VIPIN JAIN

  1. include static scripts on pages that need to use them (IE contain a lightbox, then include the lightbox script)
  2. Problem solved. Do not load scripts using AJAX
  3. Make necessary function calls to the static scripts using AJAX callbacks

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