正文

Ajax返回值类型与用法实例分析(ajax返回的数据格式)学会了吗

文章摘要

这篇文章介绍了如何使用Ajax技术处理不同数据类型的返回值,包括XML、HTML和JSON格式。文章通过三个独立的测试案例(test1、test2、test3)展示了如何通过`XMLHttpRequest`对象发送请求,并根据返回内容更新页面。具体来说: 1. **test1**:用于处理XML返回值。通过解析XML中的`book`节点提取书名和简介信息。 2. **test2**:用于处理HTML返回值。直接将HTML内容渲染到页面。 3. **test3**:用于处理JSON返回值。通过解析JSON数据提取书籍信息。 文章重点介绍了如何根据不同的返回值类型重写回调函数,并使用DOM和`eval`方法处理响应内容。三个测试案例展示了Ajax在不同场景下的应用方法。

 <!DOCTYPE html> <html> <head> <meta charset=”utf-8″> <meta http-equiv=”X-UA-Compatible” content=”IE=edge”> <title>Ajax返回值类型</title> <link rel=”stylesheet” href=”https://www.jb51.net/article/”> </head> <script> //创建XMLHttpRequest对象 function createXhr(){ var xhr=null; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest();//谷歌、火狐等浏览器 }else if(window.ActiveXObject){ xhr=new ActiveXObject(“Microsoft.XMLHTTP”);//ie低版本 } return xhr; } //测试返回值为xml function test1(){ //1、创建XMLHttpRequest var xhr=createXhr(); //2、确定请求参数 xhr.open(‘GET’,’https://www.jb51.net/article/07-returntype-xml.php’,true); //3、重写回调函数 xhr.onreadystatechange=function (){ if(xhr.readyState==4 && xhr.status==200){ var domxml=xhr.responseXML; var name=domxml.getElementsByTagName(‘book’)[0].firstChild.firstChild.wholeText; var intro=domxml.getElementsByTagName(‘book’)[0].lastChild.firstChild.wholeText; document.getElementById(‘name’).value=name; document.getElementById(‘intro’).value=intro; } } //4、发送请求 xhr.send(null); } //测试返回值为文本-HTML function test2(){ //1、创建XMLHttpRequest var xhr=createXhr(); //2、确定请求参数 xhr.open(‘GET’,’https://www.jb51.net/article/07-returntype-html.php’,true); //3、重写回调函数 xhr.onreadystatechange=function (){ if(xhr.readyState==4 && xhr.status==200){ var domxml=xhr.responseXML; document.getElementById(‘area’).innerHTML=xhr.responseText; } } //4、发送请求 xhr.send(null); } //测试返回值为文本-json function test3(){ //1、创建XMLHttpRequest var xhr=createXhr(); //2、确定请求参数 xhr.open(‘GET’,’https://www.jb51.net/article/07-returntype-json.php’,true); //3、重写回调函数 xhr.onreadystatechange=function (){ if(xhr.readyState==4 && xhr.status==200){ var result=eval(‘(‘+xhr.responseText+’)’); document.getElementById(‘name’).value=result.name; document.getElementById(‘intro’).value=result.intro; } } //4、发送请求 xhr.send(null); } </script> <body> <p>书名:<input type=”text” id=”name”/></p> <p>简介:<input type=”text” id=”intro”/></p> <input type=”button” onclick=”test1();” value=”测试xml”/> <input type=”button” onclick=”test2();” value=”测试HTML” /> <input type=”button” onclick=”test3();” value=”测试json” /> <p id=”area”></p> </body> </html>