我希望在php中提交表单后查看jquery成功消息。我试过以下代码。但它没有出现。但是当我在html中编码它时它正在工作。但它不是在提交之后。我怎样才能实现它?
这是我在php中的javascript代码
<?php
if(isset($_POST['aaa']) and $_POST['aaa']=="Submit"){
echo '<html>
<style type="text/css" media="screen">
<!--
.container {width: 670px; margin: 10px auto;}
.messagebox {background-color: #F5F5F5;padding:5px;margin:10px 0px;border: 1px solid #DBDBDB;}
.errorbox {color:#000;background-color:#ffeded;padding:5px;margin:10px 0px;border:1px solid #f27c7c;}
.confirmbox {background-color:#F2FFDB;color:#151515;border:1px solid #9C6;margin:10px 0px;padding:5px;}
-->
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script >
<!--
$(document).ready(function() {
$("#messageBox").addClass("messagebox");setTimeout(function(){
$("#messageBox").fadeOut("slow")}, 4000);
});
function messagebox(){
$("#messageBox").removeClass().addClass("confirmbox").html("Item has been saved").fadeIn(2000).fadeOut(4000);
}
function alertbox(){
$("#messageBox").removeClass().addClass("errorbox").html("Oops, there was an error!").fadeIn(2000).fadeOut(4000);
}
-->
messagebox();
</script>
<body>
<div class="messagebox" id="messageBox" style="display:none;"></div>
</body>
</html>';
}
?>
答案 0 :(得分:1)
您的代码存在一些问题,但要回答您的问题,您需要使用ajax调用脚本,并在回调函数中显示消息:
$.ajax({
url: "test.php",
data: data,
success: function(message){
//this will be called once the php has returned an answer
$("#messageBox").removeClass().addClass("confirmbox").html(message).fadeIn(2000).fadeOut(4000);
}
})
<强> PHP 强>
//after processing the data, echo a response:
echo "Message has been saved";
//if an error occured, echo it
echo "an error occured";
<强>更新强>
不要在PHP echo中输出整个页面。只需关闭php标记并使用常规HTML:
<?php
if(isset($_POST['aaa']) and $_POST['aaa']=="Submit"):?>
<html>
//regular html code goes here
<?php endif;?>
查看here了解更多示例。
您没有任何按钮或表单。你应该拥有的是:
<form action="myscript.php" method="post">
<input name="email" type="text"/>
//some more inputs
<input value="Submit" type="submit"/>
</form>
现在您可以将事件绑定到表单提交并调用ajax:
$('form').submit(function(){
$.ajax({
url: "test.php",
data: $(this).serialize(),
success: function(message){
//this will be called once the php has returned an answer
$("#messageBox")
.removeClass()
.addClass("confirmbox")
.html(message)
.fadeIn(2000).fadeOut(4000);
}
})
});
听起来你真的需要学习一些关于网站开发的东西,我建议你开始here,网上有很多很棒的资源。