This article mainly shares with you the example code of JS implementation of Ajax, hoping to help everyone.
The core steps to implement Ajax:
1. Define the object;
2. Open the link;
3. Send data;
4. Process the response status;
5. DOM rendering
1. Why do we need to define objects?
The XMLHttpRequest object is the basis of Ajax. Its function is to be used in the background to realize data exchange between the client and the server.
So:
" var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Micorsoft.XMLHTTP'); //在IE5和IE6中只有 ActiveXObject('Micorsoft.XMLHTTP') 能够实现数据交互 } " " <body> <ul id="showCon"> </ul> <script type="text/javascript"> var oU = document.getElementById("showCon"); //1.创建对象 var xhr; //做兼容 if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ //IE5 IE6 xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // console.log(xhr.readyState);//0 //2.打开连接 xhr.open("GET","http://datainfo.duapp.com/shopdata/getclass.php"); // console.log(xhr.readyState);//1 //3.发送请求(数据) xhr.send(); //4.获取到数据,渲染页面 xhr.onreadystatechange = function(){ // console.log(xhr.readyState); if(xhr.readyState == 4 && xhr.status == 200){ // console.log(xhr.responseText); var t = xhr.responseText; //get方法获取的是:字符串.我们需要将其转换成JSON数据进行操作 var data1 = JSON.parse(t); //字符串====>json数据!!!!!!!!!! //json====>字符串 JSON.stringify(data1) for(var i = 0;i < data1.length;i++){ //因为这里获得的是一个数组,所以首选的是for循环 var oLi = document.createElement("li"); oLi.textContent = data1[i].className; //每一个对象下面的className值====>创建的每一个li元素 oU.appendChild(oLi); } // 注意点: // 1.字符串===>json // 2.获取每一个对象里的className的值 // |--第一步:想到利用for循环得到data1中的每一个元素 // |--第二步:因为ul中,没有li元素,所以需要进行DOM元素创建;(其实这里可以直接想到:既然创建,必定要进行"添加") // |--第三步:把转换之后的 对象[i].className ====> 对应创建的li // |--第四步:把赋过值得li追加到ul中 } } </script> </body> "
Related recommendations:
JavaScript implementation of Ajax asynchronous request examples detailed explanation
Native JavaScript implements Ajax asynchronous request
jQuery implements Ajax to verify user name uniqueness
The above is the detailed content of js implementation of Ajax example code. For more information, please follow other related articles on the PHP Chinese website!