[英]My PHP file doesn't run the JavaScript code
我已经发布了完整的代码,但是问题出在foreach循环中的按钮上。 我做了一个onclick JavaScript函数,但是当我单击按钮时,什么也没有发生。 有人可以给我提示吗?
我相信其余的一切都很好。
这是代码:
</style>
</head>
<body style="background-color:lightgrey;">
<script "text/javascript">
function show_your_message(subject,message){
<?php echo "1" ?>
$_SESSION['subject'] = subject;
$_SESSION['message'] = message;
location.href = 'show_messgae.php';
}
</script>
<?php
require 'db.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
$id = $_SESSION['email'];
$sql = "SELECT * FROM account_inbox WHERE inbox_user = '$id'";
$result=mysqli_query($conn,$sql);
$rowcount=mysqli_num_rows($result);
$type_array = array();
$from_user_array = array();
$page_link_array = array();
$message_array = array();
$subject_array = array();
while($row = $result->fetch_assoc()) {
array_push($type_array,$row['type']);
array_push($from_user_array,$row['from_user']);
array_push($page_link_array,$row['page_link']);
}
$sql = "SELECT * FROM private_messages WHERE to_user = '$id'";
$result=mysqli_query($conn,$sql);
while($row = $result->fetch_assoc()) {
array_push($message_array,$row['message']);
array_push($subject_array,$row['subject']);
}
include 'header.php';
if (isset($_SESSION["email"]) && !empty($_SESSION["email"])) {
?>
<section id="middle_table">
<div class='post feed'>
<div class="wrapper">
<table>
<tr>
<th>from</th>
<th>message type</th>
<th>Go to message</th>
</tr>
<?php foreach (range(0, $rowcount - 1) as $i): ?>
<tr>
<td><?php echo $from_user_array[$i]; ?></td>
<td><?php echo $type_array[$i]; ?></td>
<td><button onclick="show_your_message('<?php
echo $subject_array[$i]; ?>','<?php echo $message_array[$i]; ?>') "> Click to open</button></td>
</tr>
<?php endforeach; ?>
</table>
<div class="wrapper">
<input type="button" class="button" value="Next" style="float: right; cursor: pointer;">
<input type="button" class="button" value="Previous" style="float: right; cursor: pointer;">
</div>
</div>
</div>
</section>
</body>
</html>
<?php }
else {
echo "<h1> You are not logged in </h1>";
} ?>
您无法在此处尝试使用JavaScript设置PHP变量:
function show_your_message(subject,message){
<?php echo "1" ?>
$_SESSION['subject'] = subject;
$_SESSION['message'] = message;
location.href = 'show_messgae.php';
}
这应该抛出错误消息(请检查浏览器的控制台),因为您甚至没有将SESSION值放入PHP标记中。
为了从JavaScript设置SESSION变量,您必须使用AJAX将值发送到PHP脚本进行处理。 请记住,远程设置SESSION变量可能会出现问题,因为除非您在设置变量后重新加载当前页面,否则它们不会像您期望的那样反映在当前页面中。
另一种选择是进行页面重新加载(无需JavaScript),在该页面中您可以设置SESSION值。
扩展一下Jay所说的内容 ,并考虑到我认为您要完成的工作,您可以将javascript函数替换为:
function show_your_message(subject,message){
location.href = "show_message.php?subject=" + subject + '&message=' + message;
}
在show_message.php
您将从查询字符串中获取值并将其设置在PHP文件中。
根据主题和消息的大小,查询字符串可能不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.