[英]Ajax form validation with php WITHOUT jQuery
我正在學習沒有jQuery的JavaScript。
現在,我正在嘗試將一些數據從輸入字段傳遞給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
,它為您完成了所有這些工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.