我正在ajax和php上工作,我成功地从数据库中获取数据,但是ajax响应第一次显示在html中,但我想显示"成功/错误"消息每次点击
这是我的html/view代码
<script>
$(document).ready(function(){
$('#Mybtn').click(function(){
$('#MyForm').toggle(500);
});
});
</script>
<button id="Mybtn" class="btn btn-primary">Message</button>
<div id="result"></div>
<form id="MyForm" action="" method="post">
<label>Enter wallet address</label>
<input type="text" name="wallet" id="wallet" placeholder="Enter wallet address"/><br>
<label>Enter your msg</label>
<input type="hidden" name="senderwallet" id="senderwallet" value="332121212121212121" >
<input type="text" name="msg" id="msg" placeholder="Enter your msg"/><br>
<input type="submit" id="submit" class="btn btn-default" name="submit" value="Submit"/>
</form>
<script>
$(function(){
$('#submit').click(function(e){
e.preventDefault();
var wallet = $('#wallet').val();
var msg = $('#msg').val();
var senderwallet = $('#senderwallet').val();
$.ajax({
type: "POST",
url: "<?php echo base_url('main/SednMsg'); ?>",
data: {wallet:wallet,msg:msg,senderwallet:senderwallet},
success: function(data){
$('#result').html(data);
$('#result').delay(5000).fadeOut('slow');
}
});
});
});
</script>
这是我的代码在控制器,我怎么能得到"success"或";error"每次点击都有消息?我哪里错了?
function SednMsg()
{
$wallet=$_POST['wallet'];
$msg=$_POST['msg'];
$senderwallet=$_POST['senderwallet'];
$result['data'] = $this->M_main->SaveMsgs($wallet,$msg,$senderwallet);
if($result['data']=="1") {
echo '<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert">×</a>
<strong>Success!</strong>
</div>';
} else {
echo '<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert">×</a>
<strong>error!</strong>
</div>';
}
}
如果你第二次调用你的元素,你需要再次显示它。
<script>
$(function(){
$('#submit').click(function(e){
e.preventDefault();
var wallet = $('#wallet').val();
var msg = $('#msg').val();
var senderwallet = $('#senderwallet').val();
$.ajax({
type: "POST",
url: "<?php echo base_url('main/SednMsg'); ?>",
data: {wallet:wallet,msg:msg,senderwallet:senderwallet},
success: function(data){
$('#result').html(data);
**$('#result').show(); // added this line**
$('#result').delay(5000).fadeOut('slow');
}
});
});
});
</script>
尝试添加一个带有css动画的类,而不是JavaScript setInterval或setTimeout