求助:解决TypeError: Cannot read properties of undefined (reading 'trim')报错
修复TypeError: Cannot read properties of undefined (reading 'trim')错误
错误根源分析
- JavaScript侧:
fetch的响应必须手动调用response.text()/response.json()读取内容,原代码第一个then块未返回任何数据,导致后续then的data参数为undefined,调用trim()触发类型错误;同时第一个then提前执行成功逻辑,存在逻辑漏洞。 - PHP侧:仅设置HTTP状态码,未输出任何响应内容,JS端无法获取验证结果标识。
代码修改方案
1. JavaScript代码修改
调整fetch的then链,先读取响应内容再处理逻辑:
function validate_submit(thisForm, action, formData) { fetch(action, { method: 'POST', body: formData, headers: {'X-Requested-With': 'XMLHttpRequest'} }) .then(response => { // 先判断响应状态,失败直接抛出错误 if(!response.ok) { throw new Error(`${response.status} ${response.statusText} ${response.url}`); } // 读取响应文本,传递给下一个then处理 return response.text(); }) .then(data => { thisForm.querySelector('.loading').classList.remove('d-block'); if (data.trim() == 'OK') { thisForm.querySelector('.sent-message').classList.add('d-block'); thisForm.reset(); } else { throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action); } }) .catch((error) => { displayError(thisForm, error); }); }
2. PHP代码修改
在设置状态码后输出对应响应内容:
if(!$validate_status) { header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request"); echo "Validation failed"; // 输出验证失败信息 } else { header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); echo "OK"; // 输出成功标识,与JS端判断逻辑对应 }
验证说明
修改后,PHP会返回明确的响应内容,JS端通过response.text()读取后,data不再是undefined,可以安全调用trim()方法;同时成功逻辑仅在服务器返回'OK'时执行,避免了原逻辑的提前触发问题。
内容的提问来源于stack exchange,提问作者jcesarfranco
相关产品推荐
相关产品推荐

