[英]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.