$cache[$key] = empty($arr) ? NULL : $arr; return $cache[$key]; } // 门户 获取需要在频道显示的栏目主题数据 function portal_channel_thread($fid) { global $forumlist; if (empty($fid)) return NULL; $orderby = array('tid' => 1); $page = 1; // 遍历所有在频道显示内容的栏目 $category_forumlist = channel_category($fid); $arrlist = array(); $forum_tids = array(); $tidlist = array(); if ($category_forumlist) { foreach ($category_forumlist as &$_forum) { // 频道显示数据 $arrlist['list'][$_forum['fid']] = array( 'fid' => $_forum['fid'], 'name' => $_forum['name'], 'rank' => $_forum['rank'], 'type' => $_forum['type'], 'url' => $_forum['url'], 'channel_new' => $_forum['channel_new'], ); $forum_thread = thread_tid__find(array('fid' => $_forum['fid']), $orderby, $page, $_forum['channel_new'], 'tid', array('tid')); // 最新信息按栏目分组 foreach ($forum_thread as $key => $_thread) { $forum_tids[$key] = $_thread; } unset($forum_thread); } $tidlist += $forum_tids; } unset($category_forumlist); // 获取属性对应的tid集合 list($flaglist, $flagtids) = flag_thread_by_fid($fid); empty($flagtids) || $tidlist += $flagtids; unset($flagtids); // 频道置顶 $stickylist = sticky_list_thread($fid); empty($stickylist) || $tidlist += $stickylist; // 在这之前合并所有二维数组 tid值为键/array('tid值' => tid值) $tidarr = arrlist_values($tidlist, 'tid'); // 在这之前使用$tidarr = array_merge($tidarr, $arr)前合并所有一维数组 tid/array(1,2,3) if (empty($tidarr)) { $arrlist['list'] = isset($arrlist['list']) ? array_multisort_key($arrlist['list'], 'rank', FALSE, 'fid') : array(); return $arrlist; } $tidarr = array_unique($tidarr); $pagesize = count($tidarr); // 遍历获取的所有tid主题 $threadlist = well_thread_find_asc($tidarr, $pagesize); // 遍历时为升序,翻转为降序 $threadlist = array_reverse($threadlist); foreach ($threadlist as &$_thread) { // 各栏目最新内容 isset($forum_tids[$_thread['tid']]) AND $arrlist['list'][$_thread['fid']]['news'][$_thread['tid']] = $_thread; // 全站置顶内容 isset($stickylist[$_thread['tid']]) AND $arrlist['sticky'][$_thread['tid']] = $_thread; // 首页属性主题 if (!empty($flaglist)) { foreach ($flaglist as $key => $val) { if (isset($val['tids']) && in_array($_thread['tid'], $val['tids'])) { $arrlist['flaglist'][$key][array_search($_thread['tid'], $val['tids'])] = $_thread; ksort($arrlist['flaglist'][$key]); $arrlist['flag'][$_thread['tid']] = $_thread; } } } } unset($threadlist); if (isset($arrlist['sticky'])) { $i = 0; foreach ($arrlist['sticky'] as &$val) { ++$i; $val['i'] = $i; } } if (isset($arrlist['flag'])) { $i = 0; foreach ($arrlist['flag'] as &$val) { ++$i; $val['i'] = $i; } } if (isset($arrlist['flaglist'])) { foreach ($arrlist['flaglist'] as &$val) { $i = 0; foreach ($val as &$v) { ++$i; $v['i'] = $i; } } } isset($arrlist['list']) AND $arrlist['list'] = array_multisort_key($arrlist['list'], 'rank', FALSE, 'fid'); return $arrlist; } ?>javascript - How to include js file in ajax call? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to include js file in ajax call? - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Apr 20, 2010 at 8:19 AnubhawAnubhaw 1011 gold badge1 silver badge3 bronze badges 1
  • 1 I had a similar question, not long ago, that I found an answer for, where I was trying to load jQuery. The info in it may help you? stackoverflow.com/questions/3129451/… – jasonpgignac Commented Aug 4, 2010 at 18:33
Add a comment  | 

7 Answers 7

Reset to default 2

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

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.

May want to try running some prepatory javascript in the :before option to setup a variable with the correct files?

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
发布评论

评论列表(0)

  1. 暂无评论