This time I will bring you ajax and cross-domain jsonp. What are the precautions for ajax and cross-domain jsonp? The following is a practical case, let’s take a look.
nbsp;html> <meta> <title>Title</title> <script> window.onload =function(){ var oBtn = document.getElementById('btn'); oBtn.onclick = function(){ //创建XHR对象 var xhr = new XMLHttpRequest(); //请求的方式,地址,是否异步 xhr.open('get','test.txt',true); //请求的确定操作,初始化,相当于搜索时,敲击的回车 xhr.send(null); //请求的readyState每变化一次就执行一次onreadystatechange函数 //其中readyState表示的是:请求/响应过程的当前活动阶段 //readyState有如下取值 /* * 0:未初始化,尚未调用send()方法 * 1: 启动 * 2:发送 * 3:接收 * 4:完成 */ xhr.onreadystatechange =function(){ if(xhr.readyState ==4){ alert(xhr.responseText); } } }; }; </script> <input>
nbsp;html> <meta> <title>Title</title> <style> *{ margin: 0; padding: 0; } input{ width:300px; height:30px; border:1px solid lightgray; margin-top: 150px; margin-left: 200px; padding-left: 5px; } ul{ width:307px; list-style: none; margin-left: 200px; display: none; } li{ height:30px; border: 1px solid lightgray; line-height: 30px; padding-left: 5px; } </style> <script> function callbackD(response){ var oUl = document.getElementById('ulList'); var html=''; if(response.s.length !=0){ oUl.style.display='block'; for(var i = 0;i<response.s.length;i++){ html+='<li>'+response.s[i]+'' } } oUl.innerHTML = html; } </script> <script> window.onload = function(){ //获取dom元素 var oData = document.getElementById('inputSearch'); var oUl = document.getElementById('ulList'); //键盘按下后抬起触发事件(onkeyup) oData.onkeyup = function(){ if(oData.value != ''){ //创建标签(createElement) var script = document.createElement("script"); //添加地址 script.src='http://unionsug.baidu.com/su?wd='+this.value+'&p=3&cb=callbackD'; //添加给body的(成为body包涵的孩子) document.body.appendChild(script); }else{ oUl.style.display='none'; } } }; </script> <input>
The above is the detailed content of ajax and cross-domain jsonp. For more information, please follow other related articles on the PHP Chinese website!