我在下面的代码中,我有一个由三个字段和两个按钮组成的表单。在Review按钮中,我想用阿拉伯语随机显示任何单词,并让用户通过勾选Show translation
按钮以英语显示其翻译。
<html>
<body>
<script>
function myFun1(var) {
document.getElementById("demo").innerHTML = "The translation in English is " + var;
}
</script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
<br>
<p id="demo"></p>
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
$eng = $row1['English'];
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
}
$conn->close();
?>
</body>
</html>
在代码中,以下行创建按钮并触发myFun1()
功能:
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
问题是当单击按钮时,没有任何反应(根本不显示该消息)。任何想法如何解决它?
答案 0 :(得分:2)
首先将参数 var 更改为另一个参数名称,因为 var 是javascript中的关键字
<script type="text/javascript">
function myFun(as) {
document.getElementById("demo").innerHTML = "The translation in English is " + as;
}
</script>
其次,您必须在单引号或双引号中传递字符串值以使用反斜杠\
并从 myFun()
中纠正函数名称到 myFun1()
echo '<button onClick = "myFun1(\''.$eng.'\')">Show translation</button>';
让你的代码完美无缺。
答案 1 :(得分:0)
你有函数myFun1(var)的定义,但是你正在调用myFun()。我想这就是为什么单击按钮后没有任何内容的原因。
答案 2 :(得分:-1)
在
之前将其添加到顶部&LT; html&gt;标签
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>