2017-04-11 17 views
1

我需要獲取客戶端的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); 
} 
+0

嘗試'console.log(this.responseText)'告訴我們你看到了什麼。 – mazedlx

+0

this.responseText在ajax回調中包含正確的IP還是失敗? – Shilly

+0

即時消息得到正確的IP在HTML頁面上,但當即時通訊使用JavaScript來獲得這個IP值它顯示undefined –

回答

1

首先你要確認你都可以從你的AJAX請求通過檢查正確的反應,其結果肯定是寫入元素與id屬性「IP」,而且比而不是使用:

var ip = document.getElementById('ip').value; 

您應該使用Node.textContent來獲取文本內容:

var ip = document.getElementById('ip').textContent; 

代碼示例(沒有AJAX請求):

function ip() { 
 
    document.getElementById('ip').innerHTML = '127.0.0.1'; 
 
} 
 

 
function ip2() { 
 
    setTimeout(function() { 
 
    var ip = document.getElementById('ip').textContent; 
 
    console.log(ip); 
 
    }, 1000); 
 
}
<body onload="ip(); ip2();"> 
 
<kbd id="ip" ></kbd>

+0

我做了同樣的工作,並完成了我的工作。非常感謝你!!! –

0

你想在Java腳本您的IP地址,所以必須把IP地址那個標籤我認爲。

<?php $ip_address = $_SERVER['REMOTE_ADDR'];?> 

<body onload='ip(); ip2();'> 
<kbd id='ip' ><?php echo $ip_address; ?></kbd> 
+0

以及問題是,我想PHP腳本放置不同,而不是在HTML文件 –

0
<?php echo $_SERVER['REMOTE_ADDR'];?> 
<html> 
<head> 
</head> 
<body onload='ip();'> 
<div id='ip' ></div> 
</body> 
</html> 
<script> 
function ip() { 

var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
if (this.readyState == 4 && this.status == 200) { 
    document.getElementById("ip").innerHTML = 
    this.responseText; 
    ip2(this.responseText); 
} 
}; 
xhttp.open("POST", "try.php"); 
xhttp.send(); 


} 

function ip2(stringvalue) { 
setTimeout(
     function() { 
     var ip = document.getElementById("ip").value; 
alert(stringvalue); 
     },2000); 
} 
</script> 

運行這段代碼,你會發現什麼問題。

相關問題