我正在尝试为学校项目建立一个网站。我希望在单击Submit按钮后发生schoolResponse()函数。如果我删除jQuery函数,它会工作,但当我加载页面时,它会显示一个默认值。
下面是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>NHG</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="css/normalize.css"/>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
<link type="text/css" rel="stylesheet" href="css/resposive.css"/>
</head>
<body>
<header>
<div id="main-head">
<a href="#"><h2 id="main-heading">sKoolBook</h2></a>
</div>
</header>
<section>
<div id="container">
<div id="wrapper">
<form method="POST">
<select name="school">
<option value="none" name="none">Please Select a School...</option>
<option value="NHG">New Horizon Gurukul</option>
</select>
<input type="submit" class="button"/>
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
?>
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
</form>
</div>
</div>
</section>
<footer>
</footer>
</body>
</html>
您应该使用jQuery/AJAX来完成此操作。
<script>
$('.button').click(
$.ajax({
url: 'yoururl.php',
data: $("form").serialize(), //Better to put an ID to the form or something
success: function(data){
//DO something with your data
}
})
);
</script>
要正确使用ajax请求,您应该检查其他函数。
在你的url.php中你应该这样做
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
你不能这样做。这里有一个解决方案:
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
if($_POST['school']) schoolResponse();
?>
最好将error_reporting(0);
替换为error_reporting(E_ALL);
,否则php错误将被禁用。
并删除这部分:
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
这是一个非常基本的例子