在PHP中获取JS值

时间:2017-03-23 10:02:46

标签: javascript php mysql

好的,所以,在我们谈到这一点之前,先让我先解释几件事。我正在创建一个基本游戏,你可以获得排行榜和高分。当您输了并且游戏结束时,将出现输入字段。在这里,您可以输入您的姓名并提交您的高分。

现在我的观点是:我如何获取PHP代码来获取提交给我的数据库的名称和高分。高分在Javascript代码中定义。万一你想知道,PHP代码和Javascript代码是分开的。

以下是我试图解决问题的方法,但它绝对不起作用。 PHP代码只获取名称,它获得的高分显然等于零。

在函数内部的javascript中,我尝试使用getElementById然后使用值:

document.getElementById("score").value = duck.highscore ;

<form method="post" action="index.php">
      <input type="hidden" name="submitted" value="true">
      <input type="text" name="score" id="score" value="">  
      <input type="text" id="nameInput" placeholder="your name" maxlength="12"    name="name">
      <input type="submit" id="submitted" value="Submit your highscore">      
</form>




<?php
if (isset($_POST['submitted'])) {   

// connect  to the database      
include('leaderboard.php');

$name = $_POST['name'] ;
$score = $_POST['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" ;


}   // end of main if statement
?>

1 个答案:

答案 0 :(得分:1)

To fetch the highscore you just posted from the database. 
you must make an ajax call to your server and retrieve it 
as JSON data to dynamically show the inserted values to the
input field. And finally use


<script>
$.getJSON("ajax.php", function(return_data){
$.each(return_data.data, function(key,value){
var value = value.highscore; //returned scored from database
$("#score").attr("value", value);
to append the retrieved value to input value.
);
});
});
</script>



ajax.php

 <?php
 include("connection.php");
 $result=mysqli_query($conn,"select highscore from score");
 while($rec = mysqli_fetch_assoc($result)) 
 {
 $rows[] = $rec;
 }
 $json_row=json_encode(array('data' => $rows));// encode json
 echo $json_row;
 ?>