【发布时间】:2017-08-22 03:13:48
【问题描述】:
我正在尝试将一个 JS 变量输出到我的 PHP 文件中。然后让 PHP 将变量值发送到我的数据库中。 但不知何故它不起作用..
这里我有一个表单触发JS函数:(这个文件叫index.php)
<form method="post" action="index.php" onsubmit="return phpFunction()" >
<input type="hidden" name="submitted" value="true">
<input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
<input type="submit" id="submitted" value="Submit your highscore">
</form>
这里我们有JS函数:(这个文件叫做main.js)
function phpFunction () {
var php = duck.highscore ; // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;
};
最后我们得到了将值发送到我的本地服务器的 PHP 文件:(这个文件在 index.php 中)
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;
if (!mysqli_query($conn, $sqlinsert)) {
die('error inserting new record') ;
} // end of my nested if statement
$newrecord = "record added" ;
}
?>
当我按下提交按钮时,我收到如下错误消息:
【问题讨论】:
-
表单提交前不能重新导航,否则无法完成
-
我认为您可能还需要一个
=,例如:window.location.href = "index.php?score=" + php -
分数是用JS计算的吗?
-
@segFault 是的,我已经做到了。如果您查看第二个代码块。
-
@fedeisas 确实如此。
标签: javascript php jquery mysql database