这次给大家带来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中文网其它相关文章!
推荐阅读:
Vue2x图片预览插件使用步骤详解
vue-cli项目中使用Mockjs步骤解析
以上就是js封装ajax功能函数实现步骤详解的详细内容,更多请关注php中文网其它相关文章!