使用JavaScript时,为什么php结果HTML未定义

时间:2017-04-11 08:37:39

标签: javascript php html ajax

我需要获取客户端的IP。我能够通过PHP变量获得它 “$ _ SERVER [ 'REMOTE_ADDR']”。我通过AJAX请求从服务器端php获取此ip到html页面,但是当我想在JavaScript中使用此IP值时,它显示该值未定义。 任何解决方案?

PHP代码:

<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>

HTML CODE:

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);
}

JavaScript代码:

sec_in_day=86400
today = datetime.datetime.utcnow() 
print(today)

two_days_ago=today.timestamp()-(sec_in_day*2);

print("Two days ago (unix): ",datetime.datetime.fromtimestamp(two_days_ago).strftime('%Y-%m-%d %H:%M:%S.%f'))

3 个答案:

答案 0 :(得分:1)

首先,您应该通过检查结果是否确实写入id属性为“ip”的元素来验证您是否从AJAX请求中获得了正确的响应,而不是使用:

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>

答案 1 :(得分:0)

你想在java脚本中使用你的IP地址,所以我必须把ip地址放在那个标签中。

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

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

答案 2 :(得分: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>

运行此代码,您可能会发现问题所在。