0
我正在運行此代碼,我試圖根據用戶輸入顯示數據,現在沒有錯誤連接也會正常發生,但是當我輸入任何名稱時,它總是在else部分ReadyState的值是readyState的值永遠不會是4。 有人能讓我知道這些代碼中有什麼問題嗎? 這裏是我的JavaScript代碼:readyState的Ajax值總是不是4
function ajax() {
var xhr;
console.log("test");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
//xhr = new ActiveXObject('Microsoft.XMLHTTP');
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsondata = "";
xhr.open("POST", "index.php");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.success == 200) {
jsondata = JSON.parse(xhr.responseText);
document.getElementById("divId").innerHTML = jsondata[0].name;
}
} else {
console.log("request is not completed");
console.log(xhr.readyState);
}
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var element = document.getElementById("sbmt");
var elemenTxt = document.getElementById("txt");
if (element) {
element.addEventListener("click", function() {
var store = elemenTxt.value;
var storeVa = "datafound=" + store;
console.log(store);
console.log(storeVa);
xhr.send(storeVa);
})
}
}
ajax();
這是我的PHP代碼:
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
$con=mysqli_connect($dbhost,$username,$password);
mysqli_select_db($con,"trynew") or die(mysqli_error());
if (isset($_POST["datafound"])) {
$user = $_POST['datafound'];
}
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysqli_query($con,$query);
if($result==FALSE)
{
die(mysqli_error());
}
while($row = mysqli_fetch_assoc($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);
echo $jsondata;
mysqli_close($con);
?>
readyState值是什麼? – epascarello