[英]How to fix TypeError “cannot read property 'x' of null” at Array in React
[英]How to fix "TypeError: X is null"
我正在制作一個小站點/服務器,我可以在其中將我的姓名/姓氏/年齡等發送到 php 文件。 我的問題是我的 JS 不會從 HTML 中獲取我的輸入,然后更改 PHP。
確切的錯誤是:TypeError: firstName is null in Firefox
在不同的瀏覽器上嘗試過,但我得到了相同的結果(如預期)。 還嘗試將輸入 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>";
?>
您需要在 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.