我正在学习 JavaScript,但没有 jQuery。
现在我正在尝试将一些数据从输入字段传递到 php,然后将 $variable
从 php 传递到 javascript。在 jQuery 中,使用 $.ajax
可以轻松实现这一点。
但是我如何仅使用 JavaScript 来做到这一点?这是我的尝试。现在我只想传递 inputfield
中的 $_POST
内容。我此时没有进行任何验证。
我的计划是使用 php 进行验证,然后传递一条或多个错误消息。或者如果成功则显示成功消息。
但是从我的控制台日志中我只得到NULL
。
window.onload = function () {
var Input = document.querySelector('input#Input');
var InputButton = document.querySelector('button.formBtn');
InputButton.onclick = function () {
var InputRequest = new XMLHttpRequest();
InputRequest.open("POST", "ajax.php", true);
InputRequest.send();
InputRequest.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(InputRequest.response)
console.log(obj);
}
}
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Example</title>
<style>
#Input {
width: 200px;
height: 15px;
padding: 10px 0;
text-indent: 5px;
}
#Input:focus {
outline: none;
border: 1px solid lightblue;
}
</style>
</head>
<body>
<form name="form" action="ajax.php" method="post">
<input type="text" id="Input" name="inputTest">
<button type="submit" class="formBtn">Absenden</button>
</form>
<script src="ajax.js"></script>
</body>
</html>
<?php
$inputResponse = $_POST["inputTest"];
echo json_encode($inputResponse)
?>
最佳答案
您缺少一行,需要修改 send()
行以发送 POST 内容:
// You need to send the type
InputRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the post values in the send
InputRequest.send('key=value&key2=value2');
对于send()
,您必须将键和值转换为查询字符串。我认为这就是为什么这么多人使用 jQuery
,它已经为您完成了这一切。
关于javascript - 使用 php 不使用 jQuery 进行 Ajax 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599276/