我正在制作一个小的站点/服务器,可以在其中将我的姓名/姓氏/年龄等发送到php文件。 我的问题是,我的JS无法从HTML提取我的输入,然后再更改PHP。
确切的错误是:TypeError:Firefox中的firstName为null
在不同的浏览器上尝试过,但得到的结果相同(如预期)。 还尝试将输入的ID切换为名称,但效果不佳。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Lucas" content="Nothing important">
<title>Ajax form_1</title>
</head>
<body>
<h2>Form_2</h2>
<form>
<input type = "text" name = "firstName" placeholder = "voornaam">
<input type = "text" name = "lastName" placeholder = "achternaam">
<input type = "text" name = "age" placeholder = "leeftijd">
<input type = "text" name = "email" placeholder = "email">
<input type = "button" id = "submitButton" value = "submit">
</form>
<div id = "responseHere">Response comes here</div>
<script src="script.js"></script>
</body>
</html>
let firstName = document.getElementById("firstName");
let lastName = document.getElementById("lastName");
let age = document.getElementById("age");
let email = document.getElementById("email");
let submitButton = document.getElementById("submitButton");
let responseHere = document.getElementById("responseHere");
submitButton.addEventListener('click', ajax);
function ajax(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
responseHere.innerHTML = this.responseText;
}
};
let httpString = "form_1.php?firstName=" + firstName.value + "&lastName=" + lastName.value + "&age=" + age.value + "&email=" + email.value;
console.log(httpString);
xmlhttp.open("GET", httpString, true);
xmlhttp.send();
}
<?php
$firstName = $_GET['firstName'];
$lastName = $_GET['lastName']
$age = $_GET['age'];
$email = $_GET['email']
echo "<h2>Response Demo Form</h2><h3>";
echo "You submitted the following information<br><ul>";
echo "<li>Name: <strong> $firstName $lastName</strong></li>";
echo "<li>Age: $age</li>";
echo "<li>Age: $email</li>";
echo "</li></ul></h3>";
?>
答案 0 :(得分:1)
您需要在html代码中添加唯一的id属性
<form>
<input type = "text" id='firstName' name = "firstName" placeholder = "voornaam">
<input type = "text" id='lastName' name = "lastName" placeholder = "achternaam">
<input type = "text" id='age' name = "age" placeholder = "leeftijd">
<input type = "text" id='email' name = "email" placeholder = "email">
<input type = "button" id = "submitButton" value = "submit">
</form>