<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery.js"></script> <script> window.onload = function(){ //绑定click事件 document.getElementById(‘btnok‘).onclick = function(){ //模拟ajax //1.穿件ajax对象 var xhr = new XMLHttpRequest(); //2.设置回调函数 xhr.onreadystatechange = function(){ //6.判断与执行 if(xhr.readyState == 4 && xhr.status == 200){ alert(xhr.responseText); } } //3.初始化ajax对象 xhr.open(‘post‘,‘http://www.test.com/aajx.php‘); //4.设置请求头 xhr.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘); //5.发送ajax请求 xhr.send(null); } } </script> </head> <body> <input type="button" id="btnok" value="获取数据" /> </body> </html>
PHP代码如下所示:
<?php echo "hello ajax";
说明:当我们在某个域名下通过Ajax访问另外一个域名下的文件时,用于受到浏览器限制(同源策略),其不允许我们直接访问远程资源,我们把这种情况就称之为Ajax跨域请求。
Ajax技术由于受到浏览器的限制,该方法不允许跨域通信。
同源策略阻止从一个域上加载的脚本获取或操作另一个域上的文档属性。也就是说,受到请求的 URL 的域必须与当前 Web 页面的域相同。这意味着浏览器隔离来自不同源的内容,以防止它们之间的操作。
1)虽然Ajax不允许跨域请求,但是我们的script标签可以实现跨域请求操作
示例代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery.js"></script> <script> function callback(msg){ //msg = ‘hello ajax‘; alert(msg); } </script> <script language="javascript" src="http://www.test.com/aajax.php?fn=callback" ></script> </head> <body> <input type="button" id="btnok" value="OK" /> </body> </html>
PHP代码如下:
<?php $fn = $_GET[‘fn‘]; //这里接收的fn 相当于callback $str = "hello ajax"; //把最终返回结果赋值给$str echo $fn.‘("‘.$str.‘")‘; //callback("hello ajax")
原文:http://www.cnblogs.com/leigood/p/4932285.html