[英]How does one reload the contents of an element without refreshing the page after sending a form (The cake way)?
我有一個元素(評論列表和表單),該元素在我的應用程序中的許多地方都使用過。 除了需要刷新整個頁面外,它還可以正常工作。 這可能會帶來問題,尤其是當它重置您的注釋所屬的游戲時,導致所有進度都不幸丟失。 我在AJAX方面的經驗非常有限,那么用添加的注釋重新加載元素的最有效,最簡單的方法是什么?
這是我的元素:
<?php
/*
set variables:
$data : data of the parent
$type : the type of the parent
$name : (optional)unique name to avoid naming conflicts
*/
if(!isset($name)) {
$name = 0;
}
foreach($data['Comment'] as $comment){
echo '<div class="comment">'.$comment['content'].
' - '.$this->Html->link($comment['User']['username'],array('controller'=>'users','action'=>'view',$comment['User']['id']))
.'</div>';
}
echo $this->Form->create(null, array('url' => '/comments/add','id'=>'qCommentForm'));
echo $this->Html->link('Leave comment','javascript:toggleDisplay("comment'.$name.'")');
echo '<br><div id="comment'.$name.'" style="display:none;">';
echo $this->Form->input('Comment.parent_id', array('type'=>'hidden','value'=>$data[$type]['id']));
echo $this->Form->input('Comment.parent_type', array('type'=>'hidden','value'=>$type));
echo $this->Form->textarea('Comment.content',array('div'=>'false','class'=>'small','label'=>false));
echo $this->Form->submit(__('Leave comment'),array('div'=>'false','class'=>'small'));
echo '</div>';
echo $this->Form->end();
?>
好的,由於您的帖子,我對ajax有了更多的了解,但我仍然不知道如何以“蛋糕式”方式進行操作。
使用這樣的HTML:
<div id="comments">
<!-- list of comments here -->
</div>
<form method="post" action="/comments/add" id="qCommentForm">
<textarea name="Comment.content"></textarea>
<input type="submit" value="Leave comment">
</form>
您可以使用JavaScript(在本例中為jQuery)攔截提交事件並使用Ajax發送評論數據(假設PHP表單處理程序返回新評論的HTML片段):
// run on document ready
$(function () {
// find the comment form and add a submit event handler
$('#qCommentForm').submit(function (e) {
var form = $(this);
// stop the browser from submitting the form
e.preventDefault();
// you can show a "Submitting..." message / loading "spinner" graphic, etc. here
// do an Ajax POST
$.post(form.prop('action'), form.serialize(), function (data) {
// append the HTML fragment returned by the PHP form handler to the comments element
$('#comments').append(data);
});
});
});
如果PHP表單處理程序返回整個注釋列表(如HTML)而不是僅返回新注釋,則可以使用.html()
而不是.append()
:
$('#comments').html(data);
您可以在http://docs.jquery.com/找到jQuery文檔。
更新:我不是CakePHP專家,但是“蛋糕方式” AFAICT:
下載您喜歡的JavaScript庫
在您的視圖/布局中包含庫,例如
echo $this->Html->script('jquery');
在視圖/布局中編寫JsHelper緩沖區,例如
echo $this->Js->writeBuffer();
在您的控制器中包含JsHelper,例如
public $helpers = array('Js' => array('Jquery'));
使用JsHelper::submit()
而不是FormHelper::submit()
來生成將執行Ajax表單提交的提交按鈕,例如
echo $this->Js->submit('Leave comment', array('update' => '#comments'));
在您的控制器中,檢測該請求是否為Ajax請求,如果是,則使用Ajax布局進行渲染,例如
if ($this->request->is('ajax')) { $this->render('comments', 'ajax'); }
雖然不確定/是否需要RequestHandlerComponent
來考慮這一點。
我不確定cakePHP,但總的來說,這就是我在自定義應用程序中的操作方式。
form.serialize()
),然后通過ajax請求將數據發送到服務器上的某些PHP腳本。 我不了解PHP,但是使用Jsp和js,我會對某個元素進行操作以調用js,然后在其中添加類似var element = document.getElementById()..然后element.innerHTML =“ new value”抱歉如果在ypur情況下無法做到這一點
這是逐步指南,以獲取您想要實現的目標。
首先,您需要獲取代碼中所有要動態更新的部分,並為其指定一個唯一的ID。 該ID在不同頁面上可以相同,只要該ID在某個頁面上僅存在一次即可。
<div id="comments"></div>
接下來,您需要構建一個ajax請求以從表單中發布評論。 假設您有以下注釋textarea(ajax請求不需要<form>
):
<textarea name="comment" id="add_comment"></textarea>
您將執行類似於以下內容的ajax請求:
function refreshComments() { var comment = encodeURIComponent(document.getElementById('add_comment').value); var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById('comments').innerHTML = xmlhttp.responseText; } } xmlhttp.open("POST","add_comment.php?comment=" + comment, true); xmlhttp.send(); }
現在,將您的submit
按鈕更改為如下所示:
<input type="button" name="addComment" value="Add Comment" onClick="refreshComments();" />
現在,在PHP中,您將需要處理添加注釋的請求,然后需要答復該特定頁面的所有注釋。 (這將使用戶可以在閑置時看到其他用戶發布的任何評論。)您要做的就是將評論回顯到ajax頁面(示例中的add_comment.php)。
您可以在這里玩弄小提琴,以了解其工作原理: http : //jsfiddle.net/xbrCk/
先前的答案包括ajax示例代碼。 一種有效的方法是使您的php代碼返回一個JavaScript變量UID,其中包含代碼加載的最后一條消息的uid,並包含一個空的div(即)。 然后,您可以將您的ajax調用結果插入該div之前,並為變量UID設置一個新值,而不是通常使用所有消息的innerHTML。 您也可以在任何所需的時間間隔使用此變量輪詢服務器以獲取新注釋。
這是我的逐步說明:
1.首先用表單創建一個html文件,表單如下所示:
<body>
<div id="comment-list"></div>
<form id="form">
<textarea name="comment"></textarea>
<input type="button" value="Submit Comment" id="submitcomments">
</form>
</body>
2.然后像這樣調用jQuery庫:
<script language="javascript" src="<js directory>/jquery-1.7.2.js">/script>
您可以在此處獲取jquery: http : //api.jquery.com
3.然后創建一個像這樣的jquery ajax:
<script>
$(document).ready(function()
{
$("#submitcomments").click(function(){ //upon clicking of the button do an ajax post
var serializedata = $("#form").serialize(); //serialize the all fields inside the form
$.ajax({
type: 'POST',
url: 'filename.php', //some php file returning the comment list
data: serializedata,// data that will be posted on php files
success: function(data)
{
$("#comment-list").append(data); //now if the ajax post was success append the data came from php to the comment-list container in the html
}
});
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.