图像Ping
只要请求完成,就能得到通知,发送一个name参数,常用于跟踪用户点击页面或动态广告曝光次数.
缺点:
1.只能发送GET 请求
2.无法访问服务器的响应文本
<script>
var img = new Image();
img.onload = img.onerror = function(){
alert("Done!");
};
img.src = "http://www.example.com/test?name=Nicholas";
</script>
JSONP
JSONP是通过动态<script>元素来使用,可以为其src属性指定一个跨域URL
<script>
function handleResponse(response){
alert("You're at IP address " + response.ip + ", which is in " + response.city + ", " + response.region_name);
}
var script = document.createElement("script");
script.src = "http://freegeoip.net/json/?callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);
</script>
优点:可以直接访问响应文本
在使用非Web服务时,要保证其安全可靠
要确定JSONP请求是否失败也不容易
Comet
IE不支持
<script>
function createStreamingClient(url, progress, finished){
var xhr = new XMLHttpRequest(),
received = 0;
xhr.open("get", url, true);
xhr.onreadystatechange = function(){
var result;
if (xhr.readyState == 3){
//get only the new data and adjust counter
result = xhr.responseText.substring(received);
received += result.length;
//call the progress callback
progress(result);
} else if (xhr.readyState == 4){
finished(xhr.responseText);
}
};
xhr.send(null);
return xhr;
}
var client = createStreamingClient("streaming.php", function(data){
alert("Received: " + data);
}, function(data){
alert("Done!");
});
</script>
CORS
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "http://www.somewhere-else.com/xdr.php");
if (request){
request.onload = function(){
//do something with request.responseText
};
request.send();
}
确保XHR访问的URL安全
1.要求以SSL连接来访问可以通过XHR请求的资源
2.要求每一次请求都要附带验证码
注意,以下方法无效,很容易伪造
1.要求发送POST
2.检查来源URL
3.基于cookie
不要把用户名和密码放在javascrip里