我需要獲取客戶端的IP。我能夠通過PHP變量 「$ _SERVER ['REMOTE_ADDR']」得到它。我通過AJAX請求從服務器端的PHP獲得這個IP到HTML頁面,但是當我想在JavaScript中使用這個IP值時,它顯示值是未定義的。 任何解決方案?爲什麼在使用JavaScript時未定義HTML中的HTML結果
PHP代碼:
<?php echo $_SERVER['REMOTE_ADDR'];?>
HTML代碼:
<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>
JavaScript代碼:
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ip.php");
xhttp.send();
}
function ip2() {
setTimeout(function() {
var ip = document.getElementById("ip").value;
alert(ip);
}, 1000);
}
嘗試'console.log(this.responseText)'告訴我們你看到了什麼。 – mazedlx
this.responseText在ajax回調中包含正確的IP還是失敗? – Shilly
即時消息得到正確的IP在HTML頁面上,但當即時通訊使用JavaScript來獲得這個IP值它顯示undefined –