纯javascript:为什么不在ajax内容中加载脚本工作?

时间:2013-10-01 08:19:03

标签: javascript jquery ajax

这是我写的代码:

function responseAjax(element, url, loader, data) {
    if(request.readyState == 4) {
        if(request.status == 200) {
            //The response has 2 main parts: the main page element and the javascript that have the text "???PHPTOSCRIPT???" in between
            output = request.responseText.split('???PHPTOSCRIPT???');
            if (element) document.getElementById(element).innerHTML = output[0];//put first part into element
            if (output[1] != "") eval(output[1]); //execute script
            //remember the last request
            if (typeof(url) !== 'undefined') {
                document.cookie = "requestedURL=" + escape(url);
                document.cookie = "requestedElement=" + escape(element);
                document.cookie = "requestedLoader=" + escape(loader);
                document.cookie = "requestedData=" + escape(data);
            };
        };
    };
};

function ajax(url, element, loader, data, remember, async) {
    remember = (typeof(remember) === 'undefined') ? false : remember;//remember last request. Default: false
    async = (typeof(async) === 'undefined') ? true : async;//handle request asynchronously if true. Default: true

    if (loader) document.getElementById(element).innerHTML = loader;

    try { request = new XMLHttpRequest(); /* e.g. Firefox */}
    catch(err) {
        try { request = new ActiveXObject("Msxml2.XMLHTTP"); /* some versions IE */}
        catch(err) {
            try { request = new ActiveXObject("Microsoft.XMLHTTP"); /* some versions IE */}
            catch(err) { request = false;}
        }
    }

    if (request) {
        url += "?r=" + parseInt(Math.random()*999999999);//handle the cache problem
        //put an array of data into string. Default: null array
        data = data || [];
        for (var i = 0; i < data.length; i++) {
            url += "&" + data[i];
        };

        request.open("GET", encodeURI(url), async);

        url = url.split('?');//get query string for remembered request
        request.onreadystatechange = (remember) ? function() {responseAjax(element, url[0], loader, data.join('&'));}
                                                : function() {responseAjax(element)};

        request.send(null);
    } else {
        document.getElementById(element).innerHTML = "<h3>Browser Error</h3>";
    };
};

虽然我使用eval()来处理返回的脚本,但是如果我使用纯javascript,脚本根本无法处理事件。但是,如果我使用jQuery,例如$("#tab-panel").createTabs();,则此代码可以正常工作。

有人可以解释一下为什么加载的ajax内容上的纯javascript不起作用吗?

其他信息:正如我所说,通过ajax内容发送的纯{javascipt}(例如function)不适用于事件,但alert()等其他代码可以正常工作。

0 个答案:

没有答案