You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复TypeError: firstName is null?表单数据无法传递至PHP问题

解决JavaScript无法获取输入框内容的TypeError问题

嘿,我一眼就揪出你遇到的问题根源啦——你在JavaScript里用document.getElementById()来获取输入框元素,但你的HTML输入框只设置了name属性,完全没加id属性!浏览器找不到对应id的元素,自然就抛出TypeError: firstName is null这类错误咯。

下面给你两种简单直接的解决办法:

方法一:给输入框添加id属性

直接在每个input标签里补上和name一致的id,这样getElementById()就能精准定位到元素了。修改后的HTML代码如下:

<!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" 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>
<div id = "responseHere">Response comes here</div>
<script src="script.js"></script>
</body>
</html>

方法二:不修改HTML,改用其他选择器获取元素

如果你不想给输入框加id,也可以用document.querySelector()通过name属性来选择元素,修改JavaScript开头部分就行:

// 用querySelector通过name属性定位元素
let firstName = document.querySelector('input[name="firstName"]');
let lastName = document.querySelector('input[name="lastName"]');
let age = document.querySelector('input[name="age"]');
let email = document.querySelector('input[name="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;
 }
 };
 // 额外优化:给参数值加encodeURIComponent,避免特殊字符导致请求异常
 let httpString = "form_1.php?firstName=" + encodeURIComponent(firstName.value) + 
                  "&lastName=" + encodeURIComponent(lastName.value) + 
                  "&age=" + encodeURIComponent(age.value) + 
                  "&email=" + encodeURIComponent(email.value);
 console.log(httpString);
 xmlhttp.open("GET", httpString, true);
 xmlhttp.send();
}

小提醒

我给你的JS代码加了encodeURIComponent()处理参数值,这是因为如果用户输入空格、@这类特殊字符,直接拼进URL会导致请求出错,编码后就能完美避免这个问题啦。

你的PHP代码已经修正过分号错误,保持原样就可以正常运行。

内容的提问来源于stack exchange,提问作者CMDR_Garbage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:45:35