我正在尝试创建一个包含按钮“请求颜色”的HTML文档。每当用户单击“request color”时,页面都会对URL color-service.php执行Ajax POST请求。color-service.php文件处理POST请求并返回一个包含随机颜色的JSON,例如:{ color:"red“}。然后使用Ajax响应相应地更改color.html页面的背景。
当前HTML:
<!Doctype HTML>
<html>
<head>
<title>Random Color Changer</title>
</head>
<body style="<? echo $color?>">
<h1>Random Color Generator</h1>
<p id="color"></p>
<button type="button" onclick="changeColor()">Request Color</button>
<script>
function changecolor() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById.color = this.responseText;
}
}
};
xhttp.open("GET", "color-service.php", true);
xhttp.send();
}
</script>
</body>
</html>
当前PHP:
<?php
$list = array('red', 'blue', 'yellow', 'pink', 'green');
$i = array_rand($list);
$color = $list[$i];
?>
发布于 2018-10-25 02:49:28
<body style="background-color:<? echo $color?>">
确保你使用的是background-color
,否则浏览器不会知道你想要什么颜色,为了让$color
做任何事情,你需要在你的HTML中使用它之前定义它。
echo $color = $list[$i];
并确保color-servvce.php确实使用echo
返回随机颜色,否则它将只是一个空白页面。
document.body.style.backgroundColor = this.responseText;
你需要使用的JavaScript属性是.style.backgroundColor
,否则浏览器不知道你想要什么颜色。仅仅是color
本身并不能达到你想要的效果(它会设置文本的颜色)。
另外,你给你的函数起了两个不同的名字;一个名字是changeColor()
,另一个名字不是大写的“C”。
发布于 2018-10-25 03:11:04
这里有几个问题,但您需要的是:
HTML
<!Doctype HTML>
<html>
<head>
<title>Random Color Changer</title>
</head>
<body id="fillme">
<h1>Random Color Generator</h1>
<p id="color"></p>
<script>
function changecolor() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "color-service.php", true);
xhttp.onload = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('fillme').style.backgroundColor = this.responseText;
}
};
xhttp.send();
}
changecolor();
</script>
<button type="button" onclick="changecolor();">Request Color</button>
</body>
</html>
PHP
<?php
$list = array('red', 'blue', 'yellow', 'pink', 'green');
$i = array_rand($list);
$color = $list[$i];
echo $color;
?>
https://stackoverflow.com/questions/52975876
复制相似问题