【发布时间】:2014-01-10 16:44:40
【问题描述】:
我有一个包含 foreach 的 div,如下所示:
<div id="conversation">
<?php foreach($singles as $question): ?>
<div class="well well-sm">
<h4><?php echo $question['question_title']; ?></h4>
</div>
<div class="bubble bubble--alt">
<?php echo $question['question_text']; ?>
</div>
<?php endforeach; ?>
<?php foreach($information as $answer): ?>
<div class="bubble">
<?php echo $answer['answer_text']; ?>
</div>
<?php endforeach; ?>
</div>
我还有一个表格可以输入一个新的答案:
<form method="post" style="padding-bottom:15px;" id="answerForm">
<input type="hidden" id="user_id" value="<?php echo $_SESSION['user_id']; ?>" name="user_id" />
<input type="hidden" id="question_id" value="<?php echo $_GET['id']; ?>" name="question_id" />
<div class="row">
<div class="col-lg-10">
<textarea class="form-control" name="answer" id="answer" placeholder="<?php if($_SESSION['loggedIn'] != 'true'): ?>You must be logged in to answer a question <?php else: ?>Place your answer here <?php endif; ?>" placeholder="Place your answer here" <?php if($_SESSION['loggedIn'] != 'true'): ?>disabled <?php endif; ?>></textarea>
</div>
<div class="col-lg-2">
<?php if($_SESSION['loggedIn'] != 'true'): ?>
<?php else: ?>
<input type="submit" value="Send" id="newAnswer" class="btn btn-primary btn-block" style="height:58px;" />
<?php endif; ?>
</div>
</div>
</form>
我正在通过 ajax 提交表单,并且希望 div #conversation 在每次用户提交问题的答案时刷新并重新加载。现在我有以下 ajax 代码:
<script type="text/javascript">
$("#newAnswer").click(function() {
var answer = $("#answer").val();
if(answer == ''){
$.growl({ title: "Success!", message: "You must enter an answer before sending!" });
return false;
}
var user_id = $("input#user_id").val();
var question_id = $("input#question_id").val();
var dataString = 'answer='+ answer + '&user_id=' + user_id + '&question_id=' + question_id;
$.ajax({
type: "POST",
url: "config/accountActions.php?action=newanswer",
data: dataString,
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
});
return false;
});
</script>
您会注意到我已经尝试过$("#conversation").hide().html(data).fadeIn('fast');,但它没有成功完成这项工作。它只是将通过 ajax 传递的信息重新加载到 div 中,而不仅仅是重新加载 foreach。
如何刷新ajax调用成功函数中的div或<?php foreach(); ?>?
【问题讨论】:
-
你不能,PHP 是服务器端语言。您必须刷新页面或调用将返回相关数据的 PHP 脚本
-
我可以将提交的信息“附加”到相同的
#conversationdiv 中吗?让它看起来好像刷新了? -
我不确定你的意思是什么,但是当你添加一个新的 anwser 时,为什么不从你的脚本中返回所有 $question 数据。但我真的不确定你在这里寻找什么
-
我该怎么做?
-
在您的 jQuery AJAX 成功方法中,您缺少
data。你有success: function()它应该是success: function(data)
标签: javascript php jquery html ajax