我想在Ajax响应中调用JS脚本。它所做的就是将document.getElementById
脚本传递给Ajax响应文本。从ajax响应运行Javascript脚本
目前的代码返回我这个错误:Uncaught TypeError: Cannot set property 'innerHTML' of null
这与Visual Studio科尔多瓦做..
阿贾克斯:
$("#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';
";
}
当您访问它并尝试设置'innerHTML'时,带有'alertBox'的元素不在DOM中。你是否在ajax调用之前的某处添加它?如果不是,你需要先做。 – varontron
我认为让PHP返回一个成功/失败指示符并让现有的Ajax JS测试返回值并使用适当的类显示适当的消息会更容易。另外,考虑到你使用jQuery,你为什么手工编写自己的Ajax调用而不是使用'$ .ajax()'? – nnnnnn
你需要创建一个脚本元素,然后从响应中添加文本,然后将该元素添加到DOM –