我有了的foreach在他們像這樣一個div:刷新DIV與Ajax調用jQuery的
<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腳本 –
我可以將提交的信息「附加」到同一個「#對話」div中嗎?爲了使它看起來像刷新? –
我不確定要理解你的意思,但是當你添加一個新的anwser時,爲什麼不從腳本中返回所有$ question數據。但我真的不確定要了解你在這裏尋找什麼 –