gpt4 book ai didi

javascript - 如何使用 onclick 事件将 Javascript 变量传递给 PHP

转载 作者:行者123 更新时间:2023-11-30 21:05:45 24 4
gpt4 key购买 nike

我正在尝试将一个 javascript 变量传递给 PHP,以便我可以创建一个 (MySQL) 查询来返回单个记录。用户将输入一个搜索字符串,然后返回许多包含匹配字符串的记录。然后用户将选择他们想要查看的单个记录。

这是我的 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>

用户将单击 anchor 标记 (recipe_summary.php),这将触发 script.js 上的单击事件,该事件将存储 recipe_ID(这就是我迷路的地方)并将其传递给 ajax_post()。从这里我尝试将存储的变量作为 php 变量发送到“recipe_result.php”,然后我将在 MySQL 中使用它来仅返回选定的记录。

在 recipe_result.php 上 $_POST['recipe_id'] 没有被设置所以我不确定我的错误在哪里。

我不熟悉 ajax,但据我所知,ajax 似乎是解决方案。我看过很多教程(ajax_post() 中的所有内容都来 self 试图遵循的教程),但通常它们以 HTML 表单开始,然后将结果写入同一页面。

最佳答案

您的代码看起来不错,只需像这样在 php 中读取 recipe_id

echo $_POST['recipe_id']; 

同时查看 $_POST 变量 documentation

关于javascript - 如何使用 onclick 事件将 Javascript 变量传递给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46636281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com