php 如何保存和检索可编辑的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25790268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:00:04  来源:igfitidea点击:

How to save and retrieve contenteditable data

phpjqueryajaxhtmlcontenteditable

提问by Samu?l Visser

I want the admins from my website to be able to change the text of some pages. Using contentediteble would be perfect for me.
Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work for me, but I just don't understand the programming languages used to store the data enough to make it work.

我希望我网站的管理员能够更改某些页面的文本。使用 contenteditable 对我来说是完美的。
问题是我只知道如何用 PHP 编程。我在互联网上搜索了几个小时试图让它为我工作,但我只是不明白用于存储数据的编程语言足以使其工作。

This is how i would like it to work:
1. Admin hits a button 'edit'
2. div becomes editable.
3. When the admin is ready edditing, he hits a button 'save'
4. The data is saved to a file or database (don't really know what would be the best option).
5. The edited content shows up when the page is opened.

这就是我希望它的工作方式:
1. 管理员点击“编辑”按钮
2. div 变为可编辑。
3. 当管理员准备好编辑时,他点击“保存”按钮
4. 数据被保存到文件或数据库中(不知道什么是最好的选择)。
5. 打开页面时显示编辑的内容。

This is all I have for now:

这就是我现在所拥有的:

<div class='big_wrapper' contenteditable>
  PAGE CONTENT
</div>

I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
My problem is that i really have no idea how to save the edited data.
I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.

我知道如何在管理员点击“编辑”时将 div 转换为可编辑的 div。
我的问题是我真的不知道如何保存编辑过的数据。
我也不知道从文件中检索数据是否会很困难,这取决于数据的保存方式。如果将它保存到数据库中,我检索它就没有问题,但我不知道这是否可能,以及这是否是最佳选择。

Thanks for your help,

谢谢你的帮助,

Samu?l

萨缪尔



EDIT:

编辑:

@gibberish, thank you so much for your super-quick reply!
I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.

@gibberish,非常感谢您的超级快速回复!
我试图让它工作,但它仍然不起作用。我不知道我做错了什么。

Here's my code:
over_ons.php:

这是我的代码:
over_ons.php

<div class='big_wrapper' contenteditable>
  PAGE CONTENT
</div>

<input type='button' value='Send Data' id='mybutt'>

<script type="text/javascript">
  $('#mybutt').click(function(){
  var myTxt = $('.big_wrapper').html();
  $.ajax({
      type: 'post',
      url:  'sent_data.php',
      data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
  });

});
</script>

sent_data.php:

sent_data.php

<?php
 session_start();
include_once('./main.php');
include($main .'connectie.php');

$tekst=$_POST['myTxt'];

$query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";

mysql_query($query);
?>

Thanks again for your great help!
Can you also help me to make the div editable only when the user hits a button?

再次感谢您的大力帮助!
您还可以帮助我使 div 仅在用户点击按钮时可编辑吗?



SOLUTION:

解决方案

It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
I would like to share how i did this if someone wants to do the same.

我花了 2 个多星期才最终使一切正常。我必须学习 javascript、jQuery 和 Ajax。但现在它完美无缺。我什至为这种幻想添加了一些额外的东西:)
如果有人想做同样的事情,我想分享我是如何做到的。

over_ons.php:

over_ons.php:

//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php  
} ?>

<!--Editable DIV: -->
<div class='big_wrapper' id='editable'>
    <?php
        //Get eddited page content from the database
        $query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
        while($inhoud_test=mysql_fetch_array($query)){
            $inhoud=$inhoud_test[0];
        }

        //Show content
        echo $inhoud;
    ?>
</div>

<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
    <div id='sidenote'>
        <input type='button' value='Bewerken' id='sent_data' class='button' />
        <div id="feedback" />
    </div>
<?php }


As this is a pretty long and complicated file, I tried to translate most of my comments to english.
If you want to translate something that in't already translated, the original language is Dutch.
javascript.js:


由于这是一个相当长且复杂的文件,我尝试将我的大部分评论翻译成英文。
如果您想翻译尚未翻译的内容,原始语言是荷兰语。
javascript.js:

//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button

if(value == 'Verstuur bewerkingen'){
    return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});

//Make content editable
$('#sent_data').click(function(){
    var value = $('#sent_data').attr('value'); //change the name of the edit button

    if(value == 'Bewerken'){
        $('#sent_data').attr('value', 'Verstuur bewerkingen');  //change the name of the edit button
        var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
        $div.prop('contenteditable',!isEditable).toggleClass('editable')
        $('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
    }else if(value == 'Verstuur bewerkingen'){
                var pagina = $('#pagina').val();
                var editor = $('#editor').val();
                var div_inhoud = $("#editable").html();
                $.ajax({
                type: 'POST',
                url:  'sent_data.php',
                data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
                success: function(data){
                Change the div back tot not editable, and change the button's name
                    $('#sent_data').attr('value', 'Bewerken');  //change the name of the edit button
                    var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
                    $div.prop('contenteditable',!isEditable).toggleClass('editable')

                //Tell the user if the edditing was succesfully
                    $('#feedback').html(data);
                    setTimeout(function(){
                        var value = $('#sent_data').attr('value'); //look up the name of the edit button
                        if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
                        $('#feedback').text('');
                        }
                        }, 5000);
                    }
                    }).fail(function() {
                    //If there was an error, let the user know
                        $('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
                    });
    }
});


And finally,
sent_data.php:


最后,
sent_data.php

<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');

//Look up witch page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);

$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";

}
    if(mysql_query($query)){
        echo "<p class='opvallend'>Successfully saves changes.</p>";
    }else{
        echo "<p class='opvallend'>Saving of changes failed.<BR>
        Please try again.</p>";
    }
?>

采纳答案by cssyphus

Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.

使用客户端语言,例如 JavaScript(最好是 jQuery)来管理是否可以编辑输入框。

Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.

使用 AJAX 获取字段数据并将其发送到 PHP 文件,该文件会将数据保存在您的数据库中。

Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:

这是使用 jQuery 管理启用/禁用输入字段的非常简化的示例:

jsFiddle Demo

jsFiddle 演示

$('.editable').prop('disabled',true);

$('.editbutt').click(function(){
    var num = $(this).attr('id').split('-')[1];
    $('#edit-'+num).prop('disabled',false).focus();
});

$('.editable').blur(function(){
    var myTxt = $(this).val();
    $.ajax({
        type: 'post',
        url:  'some_php_file.php',
        data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
    });
});

PHP file: some_php_file.php

PHP 文件:some_php_file.php

<?php 
    $myVar = $_POST['varname'];
    $secondVar = $_POST['anothervar'];
    //Now, do what you want with the data in the vars


Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxtvariable -- I added that to show how you would add a second var of data to the ajax.

使用 AJAX 非常简单。我举了一个非常简短的例子来说明它会是什么样子。不要在 HTML 或 jQuery 中查找moreTxt变量——我添加它是为了展示如何将第二个数据变量添加到 ajax。

Here are some basic examples to bring you up to speed on ajax:

以下是一些基本示例,可让您快速了解 ajax:

AJAX request callback using jQuery

使用 jQuery 的 AJAX 请求回调



There is no short path to learning jQuery or AJAX. Read the examples and experiment.

学习 jQuery 或 AJAX 没有捷径可走。阅读示例并进行实验。

You can find some excellent, free jQuery tutorials here:

你可以在这里找到一些优秀的免费 jQuery 教程:

http://thenewboston.com

http://thenewboston.com

http://phpacademy.org

http://phpacademy.org



UPDATE EDIT:

更新编辑:

To respond to your comment inquiry:

回复您的评论查询:

To send data from a DIV to a PHP file, first you need an eventthat triggers the code. As you mentioned, on an input field, this can be the blur()event, which triggers when you leave a field. On a <select>, it can be the change()event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.

要将数据从 DIV 发送到 PHP 文件,首先需要一个触发代码的事件。正如您所提到的,在输入字段上,这可以是blur()当您离开字段时触发的事件。在 a 上<select>,它可以是change()在您选择选择时触发的事件。但是在 DIV 上……好吧,用户无法与 div 交互,对吗?触发器必须是用户执行的操作,例如单击按钮。

So, the user clicks a button -- you can get the content of the DIV using the .html()command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:

因此,用户单击一个按钮——您可以使用该.html()命令获取 DIV 的内容。(在输入框和选择控件上,您可以使用.val(),但在 DIV 和表格单元格上,您必须使用.html()。代码如下所示:

How to send DIV content after a button clicked:

单击按钮后如何发送 DIV 内容:

HTML:

HTML:

<div class='big_wrapper' contenteditable>
    PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />

jQuery:

jQuery:

$('#mybutt').click(function(){
    var myTxt = $('.big_wrapper').html();
    $.ajax({
        type: 'post',
        url:  'some_php_file.php',
        data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
    });

});

回答by vmars316

You could save the whole page clientside with this:

您可以使用以下方法保存整个页面客户端:

    <script>
function saveAs(filename, allHtml) {
allHtml =  document.documentElement.outerHTML; 
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;        
document.body.appendChild(elem);
elem.click();        
document.body.removeChild(elem);
}
}    
</script> 

hth