Javascript: Check whether text is a full HTML document efficiently
Our web application is goin开发者_开发知识库g to be deployed as part of a system with SSO. After session timeout, my XmlHttpRequests get redirected to a login page, we have no control over this.
On each AJAX response handler I must check whether the response text is a full HTML page or not. (HTML fragments and JSON are valid responses.)
I must admit I'm quite new to client side technologies. I catch full HTML pages like so:
if (data.search(/<html>/) > -1) { ... }
I assume this is horribly inefficient, relies on our conventions, and may introduce subtle bugs in the future. Especially considering there's a whole web browser there whose main purpose is parsing HTML...
Please share more elegant solutions for recognizing text as complete HTML documents!
(JQuery is already in use in the project.)
Closing edit:
I'm in a bit of a pickle in selecting one answer to accept, as the solution seems to be a composite of the two plus ideas from the comments:
I'll have separate validators for JSON and HTML fragment:
Where I'm expecting JSON, the response must be JSON.
Where I'm expecting an HTML fragment (and not a complete document) the response must end in a closing tag (disregarding whitespace), but not (case insensitive). The SSO login page will have to end in , we'll document this "limitation".
Thanks everyone for contributing!
If you want to check whether the response is a full HTML page you probably want to start looking at the end, don't you? Checking whether </html>
is at the end doesn't waste much performance. If you don't want that, please clarify what you mean by full HTML page.
You could use parseJson() on your response. If it returns an object it was a json, otherwise it was an html fragment
responsetrial = $.parseJson(response);
if(typeof reponsetrial ==='object'){
//it's json
}else{
//it's html
精彩评论