Asynchronous JavaScript and XML (Ajax ) 是驱动新一代 Web 站点(流行术语为 Web 2.0 站点)的关键技术。Ajax 允许在不干扰 Web 应用程序的显示和行为的情况下在后台进行数据检索。使用 XMLHttpRequest 函数获取数据,它是一种 API,允许客户端 JavaScript 通过 HTTP 连接到远程服务器。Ajax 也是许多 mashup 的驱动力,它可将来自多个地方的内容集成为单一 Web 应用程序。
同域请求
直接上代码
index.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
jsondata = xmlhttp.responseText;
var jsonobj = JSON.parse(jsondata);
document.getElementById("myDiv").innerHTML="<h3>" + jsonobj.name + "</h3>";
}
}
//GET请求方式
// xmlhttp.open("GET", "/test/demo/json/index.php?content=123", true);
// xmlhttp.send();
//POST请求方式
xmlhttp.open("POST", "http://www.a.com/test/demo/json/json.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=jack");
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
json.php
<?php
/**
*
* @authors Yiwei Xia (xyw55@foxmail.com)
* @date 2015-06-21
* @version Version1.0
*/
//下面两个header允许其他域访问,不过IE>=10,chrome,firefox支持
//header("Access-Control-Allow-Origin:*");
//header("Access-Control-Allow-Methods:POST,GET");
if (isset($_GET["content"])) {
$content = $_GET["content"];
echo "get it $content";
return;
}elseif(isset($_POST["name"])){
$name = $_POST["name"];
$arr = array('name' => $name, );
echo json_encode($arr);
return;
}
?>
跨域请求
第一种方式
CROS
在服务端加入下面两个代码,不过仅IE>=10,chrome,firefox支持,代码见上面两段
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:POST,GET");
第二种方式
采用jsonp
1、什么是JSONP?
要了解JSONP,不得不提一下JSON,那么什么是JSON ?
JSON is a subset of the object literal notation of JavaScript. Since JSON is
a subset of JavaScript, it can be used in the language with no muss or fuss.
JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。
2、JSONP有什么用?
由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源,为了实现跨域请求,可以通过script标签实现跨域请求,然后在服务端输出JSON数据并执行回调函数,从而解决了跨域的数据请求。
3、如何使用JSONP?
下边这一DEMO实际上是JSONP的简单表现形式,在客户端声明回调函数之后,客户端通过script标签向服务器跨域请求数据,然后服务端返回相应的数据并动态执行回调函数。
代码如下
index.html
<html>
<head>
<script type="text/javascript">
//回调函数
function userinfo(result){
document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";
}
function get_userinfo(){
var eleScript= document.createElement("script");
eleScript.type = "text/javascript";
eleScript.src = "http://www.a.com/test/demo/json/jsonp.php?callback=userinfo";
document.getElementsByTagName("HEAD")[0].appendChild(eleScript);
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="get_userinfo()">Change Content</button>
</body>
</html>
jsonp.php
<?php
/**
*
* @authors Yiwei Xia (xyw55@foxmail.com)
* @date 2015-06-21
* @version Version1.0
*/
if (isset($_GET["callback"])) {
$callback = $_GET["callback"];
if ($callback == "userinfo") {
$userinfo = '{"username":"jack","password":"jack"}';
//回调函数
echo $callback."($userinfo)";
}
}
?>
jQuery实现JSONP
没法按照callback返回
index2.html
<!-- jQuery -->
<html>
<head>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function get_userinfo(){
//jQuery方法1
$.getJSON("http://www.a.com/test/demo/json/jsonp.php?callback=?",
function(result) {
document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";
});
// jQuery方法2
// $.ajax({
// url:"http://www.a.com/test/demo/json/jsonp.php",
// dataType:'jsonp',
// data:'',
// jsonp:'callback',
// success:function(result) {
// document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";
// },
// timeout:3000
// });
//jQuery方法3
// $.get('http://www.a.com/test/demo/json/jsonp.php?callback=?', {name: encodeURIComponent('test')}, function (result) {document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";}, 'jsonp');
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="get_userinfo()">Change Content</button>
</body>
</html>
服务端
<?php
/**
*
* @authors Yiwei Xia (xyw55@foxmail.com)
* @date 2015-06-21
* @version Version1.0
*/
if (isset($_GET["callback"])) {
$callback = $_GET["callback"];
$userinfo = '{"username":"jack","password":"jack"}';
//回调函数
echo $callback."($userinfo)";
}
?>
Jsonp原理:
首先在客户端注册一个callback, 然后把callback的名字传给服务器。
此时,服务器先生成 json 数据。
然后以 javascript 语法的方式,生成一个function , function 名字就是传递上来的参数 jsonp.
最后将 json 数据直接以入参的方式,放置到 function 中,这样就生成了一段 js 语法的文档,返回给客户端。
客户端浏览器,解析script标签,并执行返回的 javascript 文档,此时数据作为参数,传入到了客户端预先定义好的 callback 函数里.(动态执行回调函数)
使用JSON的优点在于:
比XML轻了很多,没有那么多冗余的东西。
JSON也是具有很好的可读性的,但是通常返回的都是压缩过后的。不像XML这样的浏览器可以直接显示,浏览器对于JSON的格式化的显示就需要借助一些插件了。
在JavaScript中处理JSON很简单。
其他语言例如PHP对于JSON的支持也不错。
JSON也有一些劣势:
JSON在服务端语言的支持不像XML那么广泛,不过JSON.org上提供很多语言的库。
如果你使用eval()来解析的话,会容易出现安全问题。
尽管如此,JSON的优点还是很明显的。他是Ajax数据交互的很理想的数据格式。