繁体   English   中英

如何从 responseText 属性中提取数值?

[英]How can I extract number value from responseText property?

我在使用简单的 Ajax / JavaScript / PHP 时遇到问题。 我正在使用 Ajax 调用生成随机数的 PHP 脚本。

我已成功调用脚本并在元素内显示该随机数。

但问题是,我需要将该数字用于以后的计算,并且我不知道如何将xhttp.responseText转换为数字并将其存储在 var 中。

我从.responseText得到的只是Nan ,或者undefined ,或者在这种情况下是<p id = "number">VALUE</p>

有人可以帮忙吗?

这是完整的代码:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <button id= "btn" type="button" onclick="loadDoc()">Generate number</button>
    <div id="random">
        <p id = "number"></p>
    </div>
    <script src = "javascript.js"></script>
</body>
</html>

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("number").innerHTML =
            xhttp.responseText;
        }
    };
    xhttp.open("POST", "script.php", true);
    xhttp.send();
    console.log(number);
}

//PHP

<?php
    function getRandom(){
        $rand = rand(1,16);
        return $rand;
    }
    echo getRandom();
?>

将您的 php 代码更改为

<?php
function getRandom(){
    $rand = rand(1,16);
    return $rand;
}
echo getRandom();
?>

你没有从 php 返回任何东西。 在 getRandom() function 之前添加回显

//New Edit
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button id= "btn" type="button" onclick="loadDoc()">Generate number</button>
<div id="random">
    <p id = "number"></p>
    <input type='hidden' id="number_1" value='0' />
</div>
<script src = "javascript.js"></script>
</body>
</html>

<script>
    function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("number").innerHTML = xhttp.responseText;
          document.getElementById('number_1').value = xhttp.responseText; //This sets the value in hidden field and you can use it later.
          alert(document.getElementById('number_1').value);
        }
      };
      xhttp.open("POST", "script.php", true);
      xhttp.send();
      console.log(number);
    }
</script>

要从字符串中解析数字,请使用 js function parseInt()。 并可能检查您的 php 返回任何内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM