【问题标题】:Outputting JS variable into my PHP file将 JS 变量输出到我的 PHP 文件中
【发布时间】: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" ;


}   
?>

当我按下提交按钮时,我收到如下错误消息:

error 404

【问题讨论】:

  • 表单提交前不能重新导航,否则无法完成
  • 我认为您可能还需要一个=,例如:window.location.href = "index.php?score=" + php
  • 分数是用JS计算的吗?
  • @segFault 是的,我已经做到了。如果您查看第二个代码块。
  • @fedeisas 确实如此。

标签: javascript php jquery mysql database


【解决方案1】:

你应该使用header('Location: ' . $your_next_url);从你的脚本重定向。

【讨论】:

  • 我该怎么做?我是编程新手,所以我有点难以理解你的意思
【解决方案2】:

您需要正确传递查询字符串,您缺少一个 = 字符,这会导致如下 URL:index.php?score1234 这很可能是无效的,即。 "index.php?score" + php;

在你的phpFunction() 中让它看起来像这样:

function phpFunction () {
    var php = duck.highscore ;   // duck.highscore is a number that dynamically changes 
    window.location.href = "index.php?score=" + php;   
};

【讨论】:

  • 好的,谢谢,但它仍然无法正常工作。当我按下提交按钮时,出现 404 错误。
【解决方案3】:

不要通过javascript重定向到index.php,而是尝试将score值添加到表单并提交。

// HTML Code
<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"> 
  // added hidden input for score.   
  <input type="hidden" id="score" value="" name="score"> 
</form>

// javascript code
function phpFunction () {
  var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
  // update the score field value in the HTML form
  document.getElementById('score').value = php;
  return true;
};

//PHP代码

替换

$score = $_GET['score'];

$score = $_POST['score'];

【讨论】:

  • 清除控制台并测试。还可以通过为分数提供静态值来检查。说 document.getElementById('score').value = '12';并评论 var php = duck.highscore ;
  • 完成了,我认为 onsubmit 有问题。也许这是触发函数 phpFunction() 的错误方式
猜你喜欢
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多