【发布时间】:2016-09-30 03:27:20
【问题描述】:
我想在 Ajax 响应中调用一个 JS 脚本。它的作用是将document.getElementById 脚本传递给Ajax responseText。
当前代码返回此错误:Uncaught TypeError: Cannot set property 'innerHTML' of null
这是通过 Visual Studio Cordova 完成的。
阿贾克斯:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
PHP:
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
【问题讨论】:
-
当你访问id为
alertBox的元素不在DOM中并尝试设置innerHTML。您是否在 ajax 调用之前将其附加到某处?如果不是,您需要先这样做。 -
我认为让 PHP 只返回一个成功/失败指示器并让现有的 Ajax JS 测试返回值并使用适当的类显示适当的消息会更容易。另外,鉴于您使用的是 jQuery,为什么要手动编写自己的 Ajax 调用而不是使用
$.ajax()? -
您需要创建一个脚本元素,然后从响应中添加文本,然后将该元素添加到 DOM
-
好吧,你可以这样做,但这是一件危险的事情,因为你基本上需要评估它。而且你不应该在页面加载后使用 document.write。
-
问题是
document.write()在初始页面加载后运行时会清除页面中的所有内容......然后你不能使用getElementById......没有更多元素了
标签: javascript php jquery ajax visual-studio-cordova