- 什么是Ajax?
答:Ajax是一种无需加载整个网页,就能够更新部分网页,与后台交互的技术。
- Ajax的优点?
答:能够在不更新整个页面的前提下,维护数据。这使得Web程序可以更快速的回应用户的动作,而无需加载不必要的数据。
- Ajax的缺点?
答:可能会破坏浏览器的后退和加入收藏书签等功能。
- Ajax实现原理?
答:在浏览器中,提供了一个javascript的核心类--XMLHttpRequest,该类提供的方法可以帮我们发送HTTP请求,并接收Server的响应。
- Ajax学习对象?
答:学习XMLHttpRequest核心类的属性和方法。案例一:Ajax之GETdemo1.htmldemo1.php<!DOCTYPE html> <html lang="zh" dir="ltr"><head><meta charset="utf-8"><title></title></head><body><p>用户名:<input type="text" name="name" value=""><span id='rep'></span></p></body><script>//获取DOM对象var ipt = document.getElementsByName('name')[0];ipt.onblur = function(){var xhr = new XMLHttpRequest();xhr.open('get','demo1.php?name='+ipt.value,true);console.log(ipt.value);xhr.send(null);var sp = document.getElementById('rep');xhr.onreadystatechange = function(){//判断请求状态if(this.readyState == 4){if(this.responseText == 1) {sp.innerHTML = 'Yes';} else {sp.innerHTML = 'No';}}}}</script> </html>
<?phpif($_GET['name'] == 'jack') {echo 1;} else {echo 0;}?>
案例二:Ajax之POSTdemo2.html<!DOCTYPE html> <html lang="zh" dir="ltr"><head><meta charset="utf-8"><title></title></head><body><p>用户名:<input type="text" name="name" value=""><span id='rep'></span></p></body><script>//获取DOM对象var ipt = document.getElementsByName('name')[0];ipt.onblur = function(){var xhr = new XMLHttpRequest();xhr.open('post','demo4.php',true);xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');var data = 'name='+this.value;xhr.send(data);var sp = document.getElementById('rep');xhr.onreadystatechange = function(){//判断请求状态if(this.readyState == 4){if(this.responseText == 1) {sp.innerHTML = 'Yes';} else {sp.innerHTML = 'No';}}}}</script> </html>
demo2.php<?phpif($_POST['name'] == 'jack') {echo 1;} else {echo 0;}?>
案例三 jQuery之Ajax实现方法demo3.htmldemo3.php<!DOCTYPE html> <html lang="zh_CN"><head><meta charset="utf-8"><title></title><script type="text/javascript" src="./jq.js"></script></head><body><input type="text" name="name" value="" /></body> </html> <script type="text/javascript">$('input:text').mouseout(function(){var data ={'name':this.value}console.log(data);$.POST/GET('demo3.php',data,function(res){if(res == 1) {console.log('Yes');} else {console.log('No');}});}); </script>?>
<?phpecho $_GET/POST['name'] =='jack'?1:0; ?>