一位前同事开发了一个测验,向数据库发送结果。他被解雇但我需要再次使用该代码。我只有javascript代码,我需要重新创建php(save.php),它保存来自javascript的信息。你能帮我解决php代码还是给我一个提示。多克斯!
$(document).ready(function() {
$("#answer_a").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "a" } );
});
$("#answer_b").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "b" } );
});
$("#answer_c").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "c" } );
});
$("#answer_d").click(function() {
$.get("http://nameOfWebsite/save.php", {test: "1", question: "1", answer: "d" } );
});
});
答案 0 :(得分:2)
在save.php中使用$ _GET []来使用变量并将它们保存在表中
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$test = mysqli_real_escape_string($con, $_GET['test']);
$question = mysqli_real_escape_string($con, $_GET['question']);
$answer = mysqli_real_escape_string($con, $_GET['answer']);
$sql="INSERT INTO Persons (test, question, answer)
VALUES ('$test', '$question', '$answer')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
答案 1 :(得分:1)
使用$_GET[<name>]
获取php和mysqli_connect
中的值以将数据插入表格。
答案 2 :(得分:1)
您已经走上正轨,下一步是在PHP中。您可以使用此示例来获取这些值。考虑这个例子:
<?php
if(isset($_GET['test'])) {
$data = array(); // initialize return data holder
$test = isset($_GET['test']) ? $_GET['test'] : null;
$question = isset($_GET['question']) ? $_GET['question'] : null;
$answer = isset($_GET['answer']) ? $_GET['answer'] : null;
// they should be inside now, now you can go on with mysql inserts
// just a sample callback value to check if indeed php got it
$data['test'] = $test;
$data['question'] = $question;
$data['answer'] = $test;
echo json_encode($data);
exit;
}
?>
<!-- lets say this is an image -->
<button id="answer_a" type="button">Hi im an image</button>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#answer_a").click(function() {
$.get("index.php", {test: "1", question: "1", answer: "a" }, function(response){
var data = $.parseJSON(response);
console.log(data); // check this in console
});
});
});
</script>