我试图将存储在href链接中的变量传递给函数。我能够从查询结果中定义变量。单击超链接后,我的问题是将其传递给函数。这是我的代码:
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
{
echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
}
?>
这是功能:
<script>
function hrefClick($course){
$newCourse=$course;
}
</script>
答案 0 :(得分:0)
PHP代码:
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
{
echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
}
?>
功能应为:
<script>
function hrefClick(course){
// You can't define php variables in java script as $course etc.
var newCourse=course;
alert(newCourse);
}
</script>
答案 1 :(得分:0)
我们将在这里使用两个文件。从file1.php点击链接,我们将通过Ajax将数据发送到file2.php。这是一个基于Jquery的解决方案。
//file1.php
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
echo '<a href="javascript:void()" data-href="'.$row['courseID'].'"/>'.$row['courseID'].'</a><br>';
}
?>
<script>
$('a').click(function(){
var hrefData = $(this).attr('data-href');
if (typeof hrefData !== typeof undefined && hrefData !== false) {
alert(hrefData);
//or You can post the data
$.post( "file2.php", { courseid:hrefData} );
}
});
</script>
您可以在file2.php上检索结果
//file2.php
<?php
if(isset($_POST['courseid'])){
$newCourse = $_POST['courseid'];
}
?>
答案 2 :(得分:0)
我能找到办法让它完成吗?看起来很简单。这就是我想出来的。
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
echo "<form name='course".$row['courseID']."' action='index.php' method='GET'/>";
echo "<a href='javascript: document.course".$row['courseID'].".submit();'/>".$row['courseID']."</a>";
echo "<input type='hidden' name='courseID' value='".$row['courseID']."'/><br>";
echo "</form>";
}
?>