0

这是我写的代码:

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不起作用吗?

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

4

0 回答 0