我是初学者,我想写这个功能。但是当我尝试运行它时,为什么视图没有定义,尽管我已经定义了它。任何人都可以给我解决这个问题的方法吗?这是完整的源代码
<?php
include ("connection.php");
session_start();
$user_login = $_SESSION['user'];
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Messenger</title>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="font-awesome-4.7.0\css\font-awesome.css">
<!--Import materialize.css-->
<link rel="stylesheet" href="materialize/css/materialize.min.css" media="screen,projection"/>
<!--Import jQuery before materialize.js-->
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/js/materialize.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function viewProfile($name){
var name ='test';
alert(name);
}
</script>
</head>
<body class="blue">
<div id="chat-page">
<div id="chatbox" class="row container">
<?php
$select = mysqli_query($conn, "SELECT * FROM user WHERE Username != '$user_login'");
$row = mysqli_num_rows($select);
//echo $row_1;
if($row != 0){
while($list= mysqli_fetch_assoc($select)){
$name = $list['Username'];
echo $name;
$userFriend = mysqli_query($conn, "SELECT * FROM user WHERE Username = '$name'");
$fetch = mysqli_fetch_assoc($userFriend);
echo "<div class='friend'>";
echo "<a href='#' onclick=\"viewProfile($name)\" style='text-decoration:none'>";
if($fetch['Display Picture'])
$pic = 'avatar.jpg';
echo "<img src='".$pic."' alt='' class='circle responsive-img'>";
echo "<p>";
echo "<strong>".$fetch['Username']."</strong><br>";
echo "<span>".$fetch['Email']."</span>";
echo "</p>";
echo "</div>";
echo "</a>";
}
}else
echo "username not found";
?>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
您需要将 view()函数放在脚本标记中。还要将javascript放在页面底部。
尝试下面的代码:
<?php
echo "<div class='friend'>";
echo "<a href='#' onclick=\"view()\" style='text-decoration:none'>Click here </a>";
echo "</div>";
?>
<script>
function view(){
var name = 'Function Test';
alert(name);
}
</script>
答案 1 :(得分:0)
如果php文件中有函数,则添加<script> // js code </script>
像这样使用:
function view(){
var name = 'Test';
alert(name);
}
&#13;
<a href='#' onclick="view()" style='text-decoration:none'>Click Here</a>
&#13;
答案 2 :(得分:0)
在php代码之后将你的javascript放在底部,$name
无法识别它的存在, PHP总是在javascript 之前评估,在你的视图函数中你有php变量$name
<script type="text/javascript">
function view(){
var name = "<?php echo $name; ?>";
alert(name);
}
</script>