简体   繁体   English

发送表单后,如何在不刷新页面的情况下重新加载元素的内容(蛋糕方式)?

[英]How does one reload the contents of an element without refreshing the page after sending a form (The cake way)?

I have an element (a comments list and form) that is used in many places in my application. 我有一个元素(评论列表和表单),该元素在我的应用程序中的许多地方都使用过。 It works all fine and dandy, except it requires refreshing the entire page. 除了需要刷新整个页面外,它还可以正常工作。 This can be problematic, especially when it resets the game to which your comment belongs, causing all progress to be tragically lost. 这可能会带来问题,尤其是当它重置您的注释所属的游戏时,导致所有进度都不幸丢失。 I have very limited experience with AJAX, so what is the most effective, simplest way to reload the element with the added comment? 我在AJAX方面的经验非常有限,那么用添加的注释重新加载元素的最有效,最简单的方法是什么?

Here is my element: 这是我的元素:

<?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();
?>

Update 更新资料

Okay, so I understand a lot more about ajax thanks to your posts, but I still do not understand how to do this the "cake way". 好的,由于您的帖子,我对ajax有了更多的了解,但我仍然不知道如何以“蛋糕式”方式进行操作。

With HTML like this: 使用这样的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>

You can use JavaScript (and jQuery in this case) to intercept the submit event and send the comment data with Ajax (assuming the PHP form handler returns an HTML fragment for the new comment): 您可以使用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);
        });
    });
});

If the PHP form handler returns the whole list of comments (as HTML) instead of just the new one, you can use .html() instead of .append() : 如果PHP表单处理程序返回整个注释列表(如HTML)而不是仅返回新注释,则可以使用.html()而不是.append()

$('#comments').html(data);

You can find the jQuery documentation at http://docs.jquery.com/ . 您可以在http://docs.jquery.com/找到jQuery文档。


Update: I'm not a CakePHP expert, but the "cake way" AFAICT: 更新:我不是CakePHP专家,但是“蛋糕方式” AFAICT:

  1. Set up JsHelper : 设置JsHelper

    1. Download your preferred JavaScript library 下载您喜欢的JavaScript库

    2. Include the library in your view/layout, eg 在您的视图/布局中包含库,例如

       echo $this->Html->script('jquery'); 
    3. Write the JsHelper buffer in your view/layout, eg 在视图/布局中编写JsHelper缓冲区,例如

       echo $this->Js->writeBuffer(); 
    4. Include JsHelper in your controller, eg 在您的控制器中包含JsHelper,例如

       public $helpers = array('Js' => array('Jquery')); 
  2. Use JsHelper::submit() instead of FormHelper::submit() to generate a submit button that will do Ajax form submission, eg 使用JsHelper::submit()而不是FormHelper::submit()来生成将执行Ajax表单提交的提交按钮,例如

     echo $this->Js->submit('Leave comment', array('update' => '#comments')); 
  3. In your controller, detect if the request is an Ajax request, and if so, render using the Ajax layout, eg 在您的控制器中,检测该请求是否为Ajax请求,如果是,则使用Ajax布局进行渲染,例如

     if ($this->request->is('ajax')) { $this->render('comments', 'ajax'); } 

Not sure if/how RequestHandlerComponent figures into this though. 虽然不确定/是否需要RequestHandlerComponent来考虑这一点。

I'm not sure about cakePHP but in general, here's how I am doing it in my custom applications. 我不确定cakePHP,但总的来说,这就是我在自定义应用程序中的操作方式。

  1. Create a normal HTML form element and set all your inputs. 创建一个普通的HTML表单元素并设置所有输入。
  2. Bind an event listener (javascript) to this form to catch the submit event. 将事件监听器(javascript)绑定到此表单以捕获Submit事件。 This can be done in various ways, I am using jQuery library as it is easy to work with, especially with ajax requests. 这可以通过多种方式完成,我正在使用jQuery库,因为它易于使用,尤其是ajax请求。 You can either watch the submit button and listen to the click event or watch the form and listen for the submit event. 您可以观看“提交”按钮并收听click事件,也可以观看表单并收听“提交事件”。
  3. If the event is triggered you need to return false so the form is not really submitted. 如果触发了该事件,则需要返回false,因此不会真正提交表单。 Instead you collect your form data ( form.serialize() ) and send the data via ajax request to some PHP script on your server. 相反,您收集表单数据( form.serialize() ),然后通过ajax请求将数据发送到服务器上的某些PHP脚本。
  4. The script processes the request and sends the answer (HTML code) back to the client's browser. 该脚本处理请求,并将答案(HTML代码)发送回客户端的浏览器。
  5. Use jQuery or custom javascript to inject that returned HTML into any DOM element as you need. 根据需要,使用jQuery或自定义javascript将返回的HTML注入到任何DOM元素中。 Eg you could replace the form with the new HTML. 例如,您可以将表单替换为新的HTML。
  6. Note: Many PHP frameworks have special controllers for handling ajax requests, so does cakePHP probably, too. 注意:许多PHP框架都有特殊的控制器来处理ajax请求,cakePHP也可能如此。 This means, you need two controllers and also two views for this to work within your framework pattern. 这意味着,您需要两个控制器和两个视图才能在框架模式中工作。

我不了解PHP,但是使用Jsp和js,我会对某个元素进行操作以调用js,然后在其中添加类似var element = document.getElementById()..然后element.innerHTML =“ new value”抱歉如果在ypur情况下无法做到这一点

Here is a step by step guide to get what you want to achieve. 这是逐步指南,以获取您想要实现的目标。

  1. First, you need to get all the sections of your code that are to be updated dynamically and give them a unique id. 首先,您需要获取代码中所有要动态更新的部分,并为其指定一个唯一的ID。 The id can be the same across different pages, so long as the id exists only once on a certain page. 该ID在不同页面上可以相同,只要该ID在某个页面上仅存在一次即可。

     <div id="comments"></div> 
  2. Next, you need to build an ajax request for posting a comment from your form. 接下来,您需要构建一个ajax请求以从表单中发布评论。 Lets say you have the following comments textarea (no <form> needed for the ajax request): 假设您有以下注释textarea(ajax请求不需要<form> ):

     <textarea name="comment" id="add_comment"></textarea> 

    You would do an ajax request similar to this: 您将执行类似于以下内容的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(); } 
  3. Now change your submit button to something like this: 现在,将您的submit按钮更改为如下所示:

    <input type="button" name="addComment" value="Add Comment" onClick="refreshComments();" />

  4. Now in PHP, you will need to process the request to add the comment, then you'll need to reply with all the comments for that specific page. 现在,在PHP中,您将需要处理添加注释的请求,然后需要答复该特定页面的所有注释。 (This will allow the user to see any comments that were posted from other users while he was idle.) All you have to do is echo the comments to the ajax page (add_comment.php from the example). (这将使用户可以在闲置时看到其他用户发布的任何评论。)您要做的就是将评论回显到ajax页面(示例中的add_comment.php)。

Here is a fiddle you can play with to see the general idea of how it works: http://jsfiddle.net/xbrCk/ 您可以在这里玩弄小提琴,以了解其工作原理: http : //jsfiddle.net/xbrCk/

Previous answers include ajax sample code. 先前的答案包括ajax示例代码。 An efficient approach is to make your php code return a javascript variable UID with the uid of the last message loaded by your code and include an empty div (ie ). 一种有效的方法是使您的php代码返回一个JavaScript变量UID,其中包含代码加载的最后一条消息的uid,并包含一个空的div(即)。 Then instead of playing in general with innerHTML of all messages, your ajax call result can inserted before that div and also set a new value to variable UID. 然后,您可以将您的ajax调用结果插入该div之前,并为变量UID设置一个新值,而不是通常使用所有消息的innerHTML。 Also you can poll your server for new comments using this variable at any desired interval. 您也可以在任何所需的时间间隔使用此变量轮询服务器以获取新注释。

Here is my step by step: 这是我的逐步说明:
1. First create an html file with a form, form was look like this: 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. then call the jquery library like this: 2.然后像这样调用jQuery库:

 <script language="javascript"  src="<js directory>/jquery-1.7.2.js">/script>

You can get the jquery here: http://api.jquery.com 您可以在此处获取jquery: http//api.jquery.com
3. Then create a jquery ajax like this: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM