Friday, March 02, 2007

Different Return types from AJAX calls

When you create an XMLHTTPREQUEST object, the ResponseText can contain just about anything. In Ajaxifying old apps and widgets, I find myself dealing with two situations:

1) Output is just plain HTML

This is easy to deal with. You can just update the innerHTML of a DIV to the ResponseText.

2) Output is mixed HTML and JavaScript

This is trickier. You can run the JavaScript function eval on output that is pure JavaScript. If it's mixed, I use JavaScript to create a String that stores the HTML output I want. Then you can update the innerHTML of a DIV to be eval(ReponseText).

Also, a Caveat:

A page may fail to load. It is possible to get the return code of a page from XMLHTTPRequest, BUT, if you catch errors in your page, the page will load 'successfully' though with errors. What I've done is to print the error out in the page, and then when updating my DIV, I do ResponseText.search('ERROR'). If the result is -1, the word ERROR was not found in the text. Of course you can get more specific about the type of error...

No comments:

Labels

Blog Archive

Contributors