提交与阿贾克斯输入文本区域,然后渲染部分无需刷新整个页面文本、区域、页面、部分

2023-09-10 16:58:45 作者:放手也是种幸福

目前,我试图让没有通过JS和Ajax提交按钮评论后,它的工作原理。

问题是当后提交后,页面重新加载到 /后/:ID /注释页,我想它呈现部分,而不是刷新整个页面或带我到不同的页面。我不熟悉的JS,任何帮助将是非常美联社preciated!

这是我与我的工作:

JS与发布输入

 <脚本类型=文/ JavaScript的LANGUAGE =JavaScript的>
$(函数(){
    $('文本区域')。关键preSS(功能(E){
        如果(e.key code == 13安培;&安培;!e.shiftKey){
            即preventDefault();
           VAR FRM = this.form.submit();
            $阿贾克斯({
                网址:frm.attr(行动),
                数据:frm.serialize(),
                完成:函数(){
                    frm.submit();
                },
                数据类型:JSON
            });
        }
    });
< / SCRIPT>
 
如何导出60帧视频,让视频画面流畅无比

意见表

 < D​​IV CLASS =CommentField>
<%=的form_for([micropost,@comment]):远程=>真做| F | %>
<%= f.text_area:内容:类=> CommentText:占位符=> 写评论...%>
<%结束%GT;
< / DIV>
 

修改

评论HTML

 < D​​IV CLASS ='UserCommentContainer'>
< D​​IV CLASS ='UserPicture'>
<%= image_tag comment.user.avatar.url(:位):类=>中PP%>
< / DIV>
< D​​IV CLASS ='UserComment在'>
< D​​IV CLASS ='用户名SM'>
&其中;%=的link_to comment.user.name,user_path(comment.user)%>
< / DIV>
< D​​IV CLASS ='UserCommentText'>
&其中;%= comment.content%GT;
< / DIV>
< D​​IV CLASS ='UserCommentDate'>
&其中;%= time_ago_in_words(comment.created_at)%>
< / DIV>
< / DIV>
< / DIV>
 

解决方案

好吧,让我们试试这个试...

我觉得你想找的AJAX看起来更像是这样的:

  $('文本区域')。关键preSS(功能(E){
    如果(e.key code == 13安培;&安培;!e.shiftKey){
        即preventDefault();

        VAR myTextArea =这一点,
            FRM = this.form;

        this.disabled = TRUE;

        $阿贾克斯({
            网址:frm.attr(行动),
            数据:frm.serialize(),
            完成:函数(){
               $('< D​​IV>',{文字:myTextArea.value})。appendTo(身体);
               myTextArea.value ='';
               myTextArea.disabled = FALSE;
            },
            数据类型:JSON
        });
    }
});
 

您看到的完整的方法,我们只是附加的内容< textarea的> 的身体......你可能有你想要把一个容器在,但这种被称为客户端渲染,这意味着您正在构建的DOM(或改变它),在客户端而不是服务器...希望这有助于-ck

-----编辑----- 的

我要记你可能想要做更多的东西一样: .appendTo('#集装箱'),你有一个&LT ; DIV ID =容器> 地方在页面上,而且我相信注释需要更多的格式,什么不可以......

看看这个演示可以帮助你的想法: http://jsbin.com/ uruzul /编辑#的JavaScript,HTML,现场

-----更多的编辑----- 的

我也想这样做正确,你将不得不为利用了AJAX的回报,而我并没有包括这最初是因为它似乎并不像你在$ C具有任何概念$ C,但看到您的评论的HTML之后......你会需要你的服务器返回一个JSON对象,看起来像:

  {
    userImage:pictureUrl / image.jpg的,
    username的:这里的用户名,
    userLink:链接/到/用户/页,
    日期:2012年3月5日,
    意见:注释的文本
}
 

然后,而不是使用完整要开始使用成功错误看到文档在这里: http://api.jquery.com/jQuery.ajax/ 是这样的:

 错误:函数(jqXHR,textStatus,errorThrown){
                警报('意见提交失败\ñ\ N!'+ textStatus);
            },

            成功:功能(数据,textStatus,jqXHR){
               VAR CNT = $('< D​​IV>')
                .addClass('UserCommentContainer)
                .appendTo('CommentContainer。');

              $('< D​​IV>')
                .addClass('UserPicture)
                .appendTo(CNT)
                .append($('< IMG>',{SRC:data.userImage,类:'PP'}));

              CNT = $('< D​​IV>')
                  .addClass('UserComment在')
                  .appendTo(CNT);

              $('< D​​IV>')
                .addClass('用户名SM)
                .appendTo(CNT)
                .append($('&其中a取代;',{HREF:data.userLink,文本:data.userName}));

              $('< D​​IV>')
                .addClass('UserCommentText)
                .appendTo(CNT)
                的.text(data.comment);

              $('< D​​IV>')
                .addClass('UserCommentDate)
                .appendTo(CNT)
                .append(data.date);

               myTextArea.value ='';
            },

            完成:功能(数据,textStatus,jqXHR){
               myTextArea.disabled = FALSE;
            },
 

Currently I am trying to make a comment post without the submit button through JS and Ajax and it works.

The issue is when the post is submitted, the page reloads to the /post/:id/comment page and I would like it to render the partial rather than refresh the whole page or take me to a different page. I am unfamiliar with JS, any help would be much appreciated!

This is what I am working with:

JS for posting with enter

<script type="text/javascript" language="javascript">   
$(function(){
    $('textarea').keypress(function(e) {
        if (e.keyCode == 13 && !e.shiftKey) {
            e.preventDefault();
           var frm = this.form.submit(); 
            $.ajax({
                url: frm.attr('action'),
                data: frm.serialize(),
                complete: function(){
                    frm.submit(); 
                },
                dataType: json
            });
        }
    });
</script>

Comment Form

<div class="CommentField">
<%= form_for ([micropost, @comment]), :remote => true do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<% end %>
</div>

EDIT

Comment HTML

<div class='UserCommentContainer'>
<div class='UserPicture'>
<%= image_tag comment.user.avatar.url(:bit), :class =>"PP" %>
</div>
<div class='UserComment'>
<div class='UserName sm'>
<%= link_to comment.user.name, user_path(comment.user) %>
</div>
<div class='UserCommentText'>
<%= comment.content %>
</div>
<div class='UserCommentDate'>
<%= time_ago_in_words(comment.created_at) %>
</div>
</div>
</div>

解决方案

okay let's try this again...

I think your looking for AJAX that looks more like this:

$('textarea').keypress(function(e) {
    if (e.keyCode == 13 && !e.shiftKey) {
        e.preventDefault();

        var myTextArea = this,
            frm = this.form;

        this.disabled = true;           

        $.ajax({
            url: frm.attr('action'),
            data: frm.serialize(),
            complete: function(){
               $('<div>', { text: myTextArea.value }).appendTo('body');
               myTextArea.value = '';
               myTextArea.disabled = false;
            },
            dataType: 'json'
        });
    }
});

you see how in the complete method we are just appending the contents of the <textarea> to the body... you probably have a container you want to put that in, but this is called "client side rendering" meaning that you are building the DOM (or changing it) on the client side instead of the server... hope this helps -ck

----- edit -----

I should make note that you probably want to be doing something more like: .appendTo('#container') where you have a <div id="container"> somewhere on the page, and I am sure the comment needs more formatting and what not...

see if this demo helps you with the idea: http://jsbin.com/uruzul/edit#javascript,html,live

----- more edit -----

I also think to do this correctly you are going to have to "make use" of the AJAX return, and I didn't include this initially because it didn't seem like you had any concept of it in your code, but after seeing your comment HTML... you are going to need your server to return a JSON object that looks like:

{ 
    "userImage": "pictureUrl/image.jpg", 
    "userName": "user name here", 
    "userLink": "link/to/user/page", 
    "date": "3/5/2012", 
    "comment": "the text of the comment" 
}

and then instead of using complete you want to start using success and error see documentation here: http://api.jquery.com/jQuery.ajax/ like this:

            error: function(jqXHR, textStatus, errorThrown) {
                alert('comment submit failed!\n\n' + textStatus);
            },

            success: function(data, textStatus, jqXHR){
               var cnt = $('<div>')
                .addClass('UserCommentContainer')
                .appendTo('.CommentContainer');

              $('<div>')
                .addClass('UserPicture')
                .appendTo(cnt)
                .append($('<img>', { src: data.userImage, 'class': 'pp' }));

              cnt = $('<div>')
                  .addClass('UserComment')
                  .appendTo(cnt);

              $('<div>')
                .addClass('UserName sm')
                .appendTo(cnt)
                .append($('<a>', { href: data.userLink, text: data.userName }));

              $('<div>')
                .addClass('UserCommentText')
                .appendTo(cnt)
                .text(data.comment);

              $('<div>')
                .addClass('UserCommentDate')
                .appendTo(cnt)
                .append(data.date);

               myTextArea.value = '';
            },

            complete: function(data, textStatus, jqXHR){
               myTextArea.disabled = false;
            },