加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax学习

发布时间:2020-12-15 21:31:46 所属栏目:百科 来源:网络整理
导读:AJAX的定义 :异步JavaScript和XML。是一种用于创建快速动态网页的技术。 AJAX实例: xmlhttp; !DOCTYPE html html head script function loadXMLDoc(){ var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new Act
AJAX的定义:异步JavaScript和XML。是一种用于创建快速动态网页的技术。

AJAX实例: xmlhttp;

<!DOCTYPE html>
<html>
<head>
<script>


function loadXMLDoc(){

var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActionXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){

if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}

}

xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>我爱你,田红玲!</h2></div>
<button type="button" onclick="loadXMLDoc()">我恨你,田红玲</button>

</body>
</html>

XHR 创建XMLHttpRequest对象

XMLHttpRequest用于在后台与服务器交换数据。

语法:

variable=new XMLHttpRequest();
老版本的Internet Explorer(IE5 和 IE 6)使用ActiveX对象。
variable=new ActiveXObject("Microsoft.XMLHTTP");

为了适应所有浏览器,包括IE5,IE6,若浏览器支持XMLHttpRequest对象,则创建XMLHttpRequest对象,若不支持,则创建ActiveXOject:

var xmlhttp;

if(Window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

XHR请求:

xmlhttp.open("GET","ajax/ajax_info.txt",true);
xmlhttp.send();

语法:open(method,url,async):

method:请求的类型:GET或POST
url:文件在服务器上的位置
async:true(异步),false(同步)

send(string):将请求发送到服务器. string参数仅用于POST请求。

可以向URL添加一个唯一的ID,避免得到的是缓存的结果。

xmlhttp.open("GET","deno_get.html?t=" + Math.random(),true);
xmlhttp.send();

通过GET方法发送信息:

xmlhttp.open("GET","demo_get2.html?fname=HongLing$lname=Tian",true);
xmlhttp.send();

POST请求:

xmlhttp.open("POST","demo_post.html",true);
xmlhttp.send();

使用setRequestHeader()来添加HTTP头,然后在send()方法中规定您希望发送的数据:

xmlhttp.open("POST","ajax/ajax_test.html",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=HongLing&lname=Tian");

方法:setRequestHeader(header,value)

向请求添加HTTP头:

header:规定头的名称;
value:规定头的值

url-服务器上的文件

open()方法的url参数是服务器上文件的地址:
xmlhttp.open("GET","ajax_test.html",true);
该文件可以是任何类型的文件,比如.txt和.xml或者服务端脚本文件,比如:.asp和.php(在传回响应之前,能够在服务端上执行任务).

Async=true

当使用async=true时,请规定在响应处于onreadystatechange事件中的就绪状态时执行的函数:

xmlhttp.onreadystatechange=function(){

if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("GET","ajax_info.txt",true);
}

}

xmlhttp.open("GET","ajax/ajax_test.txt",true);
xmlhttp.send();

AJAX-服务器响应


如需获取来自服务器的响应,请使用XMLHttpRequest对象的responseText或responseXML属性。

responseText:获取字符串形式的响应数据。
responseXML:获取XML形式的响应数据。


eg1:responseText


document.getElementById("myDiv").innerHTML=xmlhttp.responseText;


eg2:responseXML


xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementByName("ARTIST");
for(i=0;i<x.length;i++){
txt=txt + x[i].childNode[0].nodeValue + "<br>"
}

document.getElementById("myDiv").innerHTML=txt;

AJAX-onreadystatechange事件

onreadystatechange事件:每当readyState改变时,就会触发onreadystatechange事件,readyState属性存有XMLHttpRequest的状态信息:

onreadystatechange():每当readyState属性改变时,就会调用该函数。
readyState:(0:请求未初始化;1:服务器连接已建立;2:请求已接收;3:请求处理中;4:请求已完成,且响应已就绪.)
status:(200:"OK";404:未找到页面);

在onreadystatechange事件中,我们规定服务器响应已做好被处理的准备时所执行的任务。当readyState等于4且状态为200时,表示响应已就绪:

xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}

}

回调函数:

如果您的网站存在多个AJAX任务,那么您应该创建XMLHttpRequest对象编写一个标准的函数,并为每个AJAX任务调用该函数. <!DOCTYPE html> <html> <head> <script> var xmlhttp; function loadXMLDoc(url,cfunc){ if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); }else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",true); xmlhttp.send(); } function myFunction(){ loadXMLDoc("/try/ajax/ajax_info.txt",function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>使用 AJAX 修改文本内容</h2></div> <button type="button" onclick="myFunction()">修改内容</button> </body> </html> AJAX-PHP实例 <!DOCTYPE html> <html> <head> <script> function showHint(str){ var xmlhttp; if(str.length=0){ document.getElementById("txtHint").innerHTML=""; return; } if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); }else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/try/ajax/gethint.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <h3>Start typing a name in the input field below:</h3> <form action=""> First name:<input type="text" id="text1" onkeyup="showHint(this.value)" /> </form> <p>Suggestion:<span id="txtHint"></span></p> </body> </html> PHP 文件 下面的代码用 PHP 编写 <?php // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; $a[]="Liza"; $a[]="Elizabeth"; $a[]="Ellen"; $a[]="Wenche"; $a[]="Vicky"; //get the q parameter from URL $q=$_GET["q"]; //lookup all hints from array if length of q>0 if (strlen($q) > 0) { $hint=""; for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],strlen($q)))) { if ($hint=="") { $hint=$a[$i]; } else { $hint=$hint.",".$a[$i]; } } } } // Set output to "no suggestion" if no hint were found // or to the correct values if ($hint == "") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?> AJAX Database实例: <html> <head> <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // IE7+,Firefox,Chrome,Opera,Safari 浏览器执行代码 xmlhttp=new XMLHttpRequest(); } else { // IE6,IE5 浏览器执行代码 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <br> <div id="txtHint"><b>Person info will be listed here.</b></div> </body> </html> PHP 文件 上面这段通过 JavaScript 调用的服务器页面是名为 "getuser.php" 的 PHP 文件。 "getuser.php" 中的源代码会运行一次针对 MySQL 数据库的查询,然后在 HTML 表格中返回结果: <?php $q=$_GET["q"]; $con = mysqli_connect('localhost','peter','abc123','my_db'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"ajax_demo"); $sql="SELECT * FROM user WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读