如何使用onclick事件将Javascript变量传递到PHP
问题描述:
我试图将一个JavaScript变量传递给PHP,以便可以创建(MySQL)查询以返回单个记录。用户将输入一个搜索字符串,然后返回许多记录包含匹配的字符串。然后用户将选择他们想要查看的单个记录。如何使用onclick事件将Javascript变量传递到PHP
这里是我的HTML(recipe_summary.php):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<table>
<tr>
<th>Recipe ID</th>
<th>Title</th>
<th>Ingredients</th>
<th>Recipe</th>
</tr>
<?php foreach($search_results as $result) { ?>
<tr>
<td><a href="#" name="<?php echo $result['recipe_id']; ?>"><?php echo $result['recipe_id']; ?></a></td>
<td><?php echo $result['title']; ?></td>
<td><?php echo $result['ingredients']; ?></td>
<td><?php echo $result['recipe']; ?></td>
</tr>
<?php }; ?>
</table>
</body>
这里是我的JS(的script.js):
$(document).ready(function() {
var myText;
$("a").click(function(){
myText = $(this).text();
ajax_post(myText);
});
function ajax_post(myText){
var hr = new XMLHttpRequest();
var url = "recipe_result.php";
var passedVal = myText;
var myVal = "recipe_id=" + myText;
hr.open("POST", url, true);
hr.setRequestHeader("Content_type","application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(myVal);
};
});
这里是recipe_result.php:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<?php
if(isset($_POST['recipe_id'])){
echo "SET";
} else {
echo "NOT SET";
}
?>
<div id="status"></div>
</body>
</html>
用户将点击一个锚标签(recipe_summary.php),这将触发script.js上的点击事件,该事件将存储recipe_ID(和th是我迷路的地方)并将它传递给ajax_post()。从这里我试图将存储的变量作为php变量发送到'recipe_result.php',然后我将在MySQL中使用该变量仅返回选定的记录。
关于recipe_result.php $ _POST ['recipe_id']没有被设置,所以我不知道我的错误在哪里。
我不熟悉ajax,但从我读过的ajax看来是解决方案。我看过很多教程(ajax_post()中的所有内容都来自我试图遵循的教程),但通常他们从HTML表单开始,然后将结果写入同一页面。
是什么'recipe_result.php'的内容? – Farnabaz
目前没有;我不确定写什么。 – RunzWitScissors
我不明白是什么问题。你有一些代码。它看起来应该做你所问的。你没有说过当你运行它时会发生什么。您尚未从开发人员工具控制台引用任何错误消息。您尚未描述在开发人员工具的网络选项卡中可见的请求和响应中的任何问题。所以......你在问什么? – Quentin