我想在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 –