</pre><p>本质上来说,AJax返回值只有两种,一种是xml、一种是text</p><p>为什么没有json?json是文本的一种,json是不是和js里面对象特别相似?有的!返回什么格式内容根据需要,很少xml,解析比较麻烦!</p><p><span style="color:#ff0000">08-returnhtml</span></p><p><span style="color:#ff0000"></span></p><p></p><pre code_snippet_id="531697" snippet_file_name="blog_20141124_2_2199769" name="code" class="html"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"> <head> <title>新建网页</title> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> function createXHR() { var xhr = null; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if(window.ActiveXObject) { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } return xhr; } function test1() { var xhr = createXHR(); xhr.open('GET','08-returntype.html',true); xhr.onreadystatechange = function() { if(this.readyState == 4) { //alert(this.responseXML); var xmldom = this.responseXML; //返回dom对象 var chs = xmldom.getElementsByTagName('book')[0]; //具体使用参考w3cschool document.getElementById('btitle').value = chs.firstChild.firstChild.wholeText; document.getElementById('bintro').value = chs.lastChild.firstChild.wholeText; } } xhr.send(null); } function test2() { var xhr = createXHR(); xhr.open('GET','08-returnhtml.PHP',true); xhr.onreadystatechange = function() { if(this.readyState == 4) { document.getElementById('news').innerHTML = this.responseText; } } xhr.send(null); } function test3() { var xhr = createXHR(); xhr.open('GET','08-returnjson.PHP',true); xhr.onreadystatechange = function() { if(this.readyState == 4) { var book = eval('('+this.responseText+')'); document.getElementById('btitle').value = book.title; document.getElementById('bintro').value = book.intro; } } xhr.send(null); } </script> <style type="text/css"> </style> </head> <body> 书名:<input type="text" id="btitle" /><br /> 简介:<input type="text" id="bintro" /><br /> <input type="button" value="测试返回XML" onclick="test1();" /> <input type="button" value="测试返回HTML代码" onclick="test2();" /> <input type="button" value="测试返回json格式" onclick="test3();" /> <div id="news"> </div> </body> </html>
08-returntype.PHP
<?PHP header('Content-Type: text/xml'); ?> <?xml version="1.0" encoding="utf-8"?> <bookstore><book bid="b008"><title>天龙八部</title><intro>人生太苦了</intro></book></bookstore>
08-returnhtml.PHP
<?PHP foreach(array('新闻1','新闻2','新闻3') as $v) { echo '<li>',$v,'</li>'; } ?>
08-returnjson.PHP
<?PHP // JavaScriptObjectNotation /* {title:'天龙八部',intro:'人生八苦'} */ $book = array('title'=>'天龙八部','intro'=>'人生八苦'); echo json_encode($book); // json_decode ?>
// Ajax realystatus 返回值
/* * 0 页面被加载
* 1 xhr.open('GET','01-vote.PHP');返回成功
* 2 服务器返回头信息接收到
* 3 接受完服务器主题信息 可能出现多次,进行分块传输时
* 4 本次请求关闭
*/
原文链接:https://www.f2er.com/ajax/166514.html