前段时间学习了AJAX,在后面要进行与后台的交互就学习了一下。
在这里,我们要知道我们要使用的东西来进行传递—form表单
form表单
在这里form表单主要还是以post和get的方式来进行提交数据
而post和get的性质我在上一节也提到过
我们有POST与GET方法 我们大多数用的是GET方法,GTE相对POST而言更简单也更快,POST适合发送大量数据的是时候(GET会将用户的部分参数例如账号密码放在url后,而POST不会,所以POST 比 GET 更稳定也更可靠)。
我们将按钮设置为type=submit就可以实现提交(重点是 这个按钮要放在form表单内)举个例子
<form action="" method="GET">
<button type="submit">登陆</button>
</form>
这上面的method就是GET与POST 而action则是你交互的地址
我们在点击这个按钮就会提交数据了
再举个例子
<form action="" method="post/get">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit">
</form>
这个就是最基本的提交 这样的提交会让页面刷新或进行跳转
AJAX
使用ajx来我们就需要用XMLHttpRequest对象来发送请求
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
就想这样 我们定义一个XMLHttpRequest对象然后用这个对象来发送数据,下面是一个例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload = function (ev) {
var oBtn = document.querySelector("button");
oBtn.onclick = function (ev1) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET" , "AA.txt" , true);
xmlhttp.send();
xmlhttp.onreadystatechange = function (ev2) {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status >= 200 && xmlhttp.status <= 300 || xmlhttp.status === 304) {
alert(xmlhttp.responseText);
}
else {
console.log("没有接受到了服务器的数据");
}
}
}
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
上诉中我们用XMLHttpRequest对象发送了请求,当状态码以及请求都成功的时候,我们就会收到服务器相应的数据。
对于前后台交互还有个websocket的方法(在学了nodeJS后还有更多的方法)只是现在都还不会,有点了解。
来源:https://blog.csdn.net/qq_44958875/article/details/100166355