2、接下来我们看response.html的代码:
复制代码 代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>该页面的路径是:http://b.com/response.html</title>
</head>
<body>
<iframe id="proxy"></iframe>
<script type="text/javascript">
function _request(reqdata, url, callback) {//通用方法,ajax请求
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
callback(data);
}
}
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send(reqdata);
}
function _getQuery(key) {//通用方法,获取url参数
var query = location.href.split("?");
var value = decodeURIComponent(query.split(key + "=").split("&")[0]);
return value;
}
function GetPerson(reqdata, callback) {//向process.php发送ajax请求
var url = "process.php";
var fn = function(data) {
var proxy = document.getElementById("proxy");
proxy.src = "http://b.com/Proxy.html?data=" + encodeURIComponent(data) + "&callback=" + encodeURIComponent(callback);
}
_request(reqdata, url, fn);
}
(function() {
var fn = _getQuery("fn");
var reqdata = _getQuery("data");
var callback = _getQuery("callback");
eval(fn + "(''" + reqdata +"'', ''" + callback + "'')");
})();
</script>
</body>
</html>
这里其实就是接收来自request.html的请求得到请求参数和方法后向服务器process.php发出真正的ajax请求,然后将从服务器返回的数据以及从request.html传过来的回调函数名传递给proxy.html。
3、接下来看一下process.php的代码,比较简单:
复制代码 代码如下:
<?php
$data = json_decode(file_get_contents("php://input"));
header("Content-Type: application/json; charset=utf-8");
echo (''{"id" : '' . $data->id . '', "age" : 24, "sex" : "boy", "name" : "huangxueming"}'');
?>
这几句代码就不打算讲了,稍微有点PHP基础都能看懂,没PHP基础的应该都能看出个大概了,呵呵~~~
4、最后就是proxy.html了:
复制代码 代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>该页面的路径是:http://a.com/proxy.html</title>
</head>
<body>
<script type="text/javascript">
function _getUrl(key) {//通用方法,获取URL参数
var query = location.href.split("?");
var value = decodeURIComponent(query.split(key + "=").split("&")[0]);
return value;
}
(function() {
var callback = _getUrl("callback");
var data = _getUrl("data");
eval("window.top." + decodeURIComponent(callback) + "(" + decodeURIComponent(data) + ")");
})()
</script>
</body>
</html>
这里也是最后一步了,proxy终于拿到了request.html透过response.html传过来的回调函数名以及从response.html直接传过来的响应数据,利用window.top执行re