在不重定向页面的情况下更新表

updating a table without redirecting the page

本文关键字:情况下 更新 重定向      更新时间:2023-09-26

如何使用 JavaScript 或 jquery 在不重定向页面的情况下更新表这是我的脚本

    function doubleclick(table,id1)
        {
            table.innerHTML="<input type=text name=tab onBlur='"javascript:submitNewName(this,'"+id1+"');'" value='""+table.innerHTML+"'">";
            table.firstChild.focus();
        }
        function submitNewName(text,id2)
        {
            text.parentNode.innerHTML=text.value;
        $.ajax({
            url: 'update',
            data:{text1:text.value,id:id2},
            type:"POST",
            dataType:"json",
            error:function(data)
            {
                alert('error')
            },
            success: function(data) 
            {
               // alert('updated!')
            }
        });  
        }

.html

<td onDblclick="javascript:doubleclick(this,${item.id});">${item.filedesc}</td>
当我双击表格时,列

内会出现一个编辑框,当文本框失去焦点(通过在表格外部单击(时调用 Onblur 事件,当它失去焦点时,应该在不重定向页面的情况下调用更新 Servlet。 更新过程应在后台进行

编辑

很抱歉编辑晚了。对我的脚本进行了一些编辑。我已经发布了我的完整工作 HTML 和 JavaScript 代码。一个月前解决了这个问题。用户请检查代码并建议是否可以进一步改进。

你可以使用 jquery 的 ajax 来实现这一点。您可以传递回调方法,以便它在实际更新完成时通知您。

这是一个表格单元格,它可以是任何东西,我在这个例子中使用div:

<div id="table-cell" editing="0">Value</div>    

js 应该是这样的

$('#table-cell').dblclick(function(){
    if ($(this).attr('editing') == '0')
    {
        // only trigger this when the cell is not in edit mode
        $(this).attr('editing',1);
        // show the input
        var input = $('<input type="text" value="'+$(this).html()+'">');
        $(this).html('');
        $(this).append(input);
        // bind blur event to input
        input.blur(function(){
            // update value from input to the table cell
            var value = $(this).val()
            $(this).parent().html(value);
            $(this).parent().attr('editing',0);
            // send the data to the server for update
            $.ajax({
                url: '/save_data/',
                data: {data:value},
                type:"POST",
                dataType:"json",
                error:function(data){alert('error')},
                success: function(data) {
                    alert('updated!')
                }
            });
        });
    }
});

使用 $.post 速记方法。

看看 http://api.jquery.com/jQuery.post/

看看 jQuery 中的 $.ajax(( 方法。在不触发页面刷新的情况下检索或发布内容非常简单。

http://api.jquery.com/jQuery.ajax/