Home >Web Front-end >JS Tutorial >Ajax Getting Started Example

Ajax Getting Started Example

无忌哥哥
无忌哥哥Original
2018-06-29 14:53:471249browse

Ajax Getting Started Example

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax入门</title>
</head>
<body>
<form action="api/check.php" method="post">
<fieldset>
<legend>用户登录</legend>
<p>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email">
</p>
<p>
<label for="password">邮箱:</label>
<input type="password" name="password" id="password">
</p>
<p><button>登录</button>
<span id="tips" style="font-size:1.2em;font-weight: bolder;color:red"></span></p>
<!-- 取消原生提交动作 -->
<!-- <p><button type="button">登录</button></p> -->
</fieldset>
</form>
</body>
</html>
<script type="text/javascript">
var btn = document.getElementsByTagName(&#39;button&#39;)[0]
btn.onclick = function () {
//获取用户提交的数据
var email = document.getElementById(&#39;email&#39;).value
var password = document.getElementById(&#39;password&#39;).value
//将用户数据组装成查询字符串
var data = &#39;email=&#39;+email+&#39;&password=&#39;+password
//1.创建xhr对象
var xhr = new XMLHttpRequest()
//2.事件监听
xhr.onreadystatechange = function (){
//5.设置回调函数
if (xhr.readyState == 4 && xhr.status == 200) {
//dom操作
var tips = document.getElementById(&#39;tips&#39;)
if (xhr.responseText == &#39;1&#39;) {
tips.innerHTML = &#39;登录成功,正在跳转中...&#39;
setTimeout(function(){
location.href = &#39;api/index.php&#39;
},2000)
} else {
tips.innerHTML = &#39;邮箱或密码错误,请重新输入&#39;
document.getElementById(&#39;email&#39;).focus()
setTimeout("tips.innerHTML = &#39;&#39;",2000)
}
}
}
//3.建立连接
xhr.open(&#39;POST&#39;,&#39;api/user.php?m=login&#39;,true)
//4.发送数据
xhr.setRequestHeader(&#39;Content-Type&#39;,&#39;application/x-www-form-urlencoded&#39;)
xhr.send(data)
return false  //禁止原按钮的提交行为
}
</script>

The above is the detailed content of Ajax Getting Started Example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn