开发者

Prototype Event.observe not seeing AJAX-returned HTML

I'm trying to create a CMS system based on AJAX using Prototype's library. On a page load, I have HTML, page title and additional Javascript for the page returned via JSON, and I update the HTML on the main area. I also have an event listener that listens for certain ID's to be clicked on.

The listener is working,

var TabMenu = {
selectedTab: 'main',
showTab: function(pid) { alert(pid); alert($(pid)); 
    $(pid).addClassName('selected'); this.selectedTab = pid;
    $(this.defaultTab).removeClassName('selected');开发者_运维问答
}};

After loading, I click on one of the new tabs, and the first "test" alert successfully alerts the element's ID, but the second alert ($(pid)) returns null. I can only surmise that the HTML returned by the AJAX request is not being evaluated and added to the DOM, otherwise it would alert [HTMLDivElement] instead of "null".

Here is the relevant AJAX call:

        new Ajax.Request(url, {
        onSuccess: function(t) {
            data = t.responseText.evalJSON();
            Page.update(data.html, data.title, data.js);
            Page.destroyLoader();
        }
    });

And here is the updating function:

update: function(data, title, js) {
    document.title = Global.title + title;
    if (title != "") { $('HEADING').update(title); }
    $('MAIN').update(data);
    if (js != "") {
        var nuJS = new Element('script', { type: 'text/javascript' }).update(js);
        $('MAIN').insert({ top: nuJS });
    }
}

Any ideas on how I can get this working?


When is the ajax request triggered? Is it triggered when you click the tab? If so the showTab function is being triggered before data has been inserted into the DOM.

If you have firebug, try using the console to select the html data, after the ajax call has finished, to see what you get. You can also use firebug's html tab to see if the data has been inserted into the DOM.

Also, even though you get the pid parameter that is set to a value, does it refer to a real id that exists in the DOM?


From your code and the comment above. I think your plan is to load all the tabs after the page loaded immediately. And hide all of them using the css. Wait until the user click the tab, Show only the one that is "selected", right?

That's mean you should change:

$('MAIN').update(data);

To something like

$('MAIN').update({after: data});

So it won't overwrite the existed one. And don't forget to move the code for document.title and eval js into showTab function.

For javascript evaluation you can insert the js into data.html and use this instead:

$('MAIN').innerHTML.evalScripts();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜