我们可以在XHTML中使用AJAX吗?

Can we use AJAX for updating a XHTML page? To connect the html page, we used to write:

   xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            document.getElementById("target").innerHTML=xhr.responseText;
        }
    }

However, we can't change innerHTML to innerXHTML, because AJAX doesn't accept it.

Yes, you can update XHTML pages using ajax. You still use innerHTML (or the DOM methods). The description of innerHTML in the HTML5 spec describes how XML vs. HTML should be treated.

Re the various DOM methods, some reading/reference material:

My first thought was "of course!". As T.J. Crowder points out, standards-compliant browsers which follow the spec should have no problem.

However, there does seem to be talk of some issues using innerHTML and maintaining well-formed XHTML markup in older versions of IE.

Keep in mind that this is old information. It may no longer be a problem.

http://www.stainlessvision.com/jquery-html-vs-innerxhtml (which uses innerHTML) http://www.stevetucker.co.uk/page-innerxhtml.php

My experience has been to the contrary, i.e. using innerHTML to insert markup is not a problem.

The AJAX piece is really irrelevant here; the question is whether or not innerHTML can be trusted to preserve the integrity of the markup being inserted into the document.

My site linked in my profile is served entirely as XHTML served as actual XHTML, application/xhtml+xml. Clicking on 'Site Options' at the top-right will in example load content via AJAX.

  • Code is not text, do not use responseText, use responseXML.
  • Never EVER use innerHTML, it's a proprietary Microsoft JScript method that is not compatible with the DOM. Using it adds huge swathes of ambiguity to your code, JavaScript may see elements you've loaded via AJAX but probably won't.
  • Use importNode as I have, these are two different document owners and you have to use importNode to load content from different documents.