這次帶給大家如何使用js封裝ajax功能函數與用法,使用js封裝ajax功能函數與用法的注意事項有哪些,下面就是實戰案例,一起來看一下。
AJAX = Asynchronous JavaScript and XML(非同步的 JavaScript 和 XML)AJAX 不是新的程式語言,而是使用現有標準的新方法。是7種技術的綜合,它包含了七個技術(javascript xml xstl xhtml dom xmlhttprequest , css), ajax 是一種黏合劑。
直接上程式:
js呼叫部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <script src= "ds.js" type= "text/javascript" charset= "utf-8" ></script>
<script type= "text/javascript" >
<span style= "white-space:pre;" > </span>window.onload= function (){
var oDs=document.getElementById( 'ds' );
var oText=document.getElementById( 'text' );
oDs.onclick= function (){
ajax( 'GET' , 'aa.txt' , '' , function (str){
console.log(str);
});
}
}
</script>
|
登入後複製
html部分:
1 2 | <input type= "button" name= "ds" id= "ds" value= "弹出" />
<input type= "text" value= "" id= "text" />
|
登入後複製
ajax封裝部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | function ajax(method, url, data, fnsuccess) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject();
}
if (method == 'GET' && data) {
url = url + '?' + data;
}
xhr.open(method, url, true);
if (method == 'GET' ) {
xhr.send(null);
} else {
xhr.setRequestHeader( 'Content-Type' , 'application/x-www-form-urlencoded' );
xhr.send(data);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
fnsuccess && fnsuccess(xhr.responseText);
} else {
alert(xhr.status);
}
}
}
}
|
登入後複製
#表單驗證,使用者名稱驗證:
1 2 3 4 5 6 | <form action= "checkName.php" method= "post" >
<!--span标签是用于提示,用户名重复,以及可以注册-->
用户名:<input type= "text" id= "username" /><span id= "inf" ></span><br />
密码:<input type= "password" /><br />
<input type= "button" id= "submit" value= "提交" />
</form>
|
登入後複製
js呼叫部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script src= "ds.js" type= "text/javascript" charset= "utf-8" ></script>
<script type= "text/javascript" >
window.onload = function () {
var oUsername = document.getElementById( 'username' );
var oInf = document.getElementById( 'inf' );
oUsername.onkeyup = function () {
var data= '&name=' + oUsername.value;
ajax( 'GET' , '/0322/test/checkName.php' ,data, function (str){
oInf.innerHTML=str;
});
}
}
</script>
|
登入後複製
php部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php
header( "Content-Type: text/xml;charset=utf-8" );
header( "Cache-Control: no-cache" );
$userName = $_GET ['name'];
if ( $userName =='admin'){
echo '<result><mes>该用户名重复了</mes></result>';
} else {
echo '<result><mes>该用户名可以注册</mes></result>' ;
}
?>
|
登入後複製
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀
JS有哪些常用數學函數?
JS裡常見內建函數使用詳解
#
以上是如何使用js封裝ajax功能函數與用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!