programing

콘텐츠 편집 가능한 데이터를 저장 및 검색하는 방법

starjava 2023. 7. 31. 21:00
반응형

콘텐츠 편집 가능한 데이터를 저장 및 검색하는 방법

저는 일부 페이지의 텍스트를 변경할 수 있기를 원합니다.을 사용하는 할 것입니다. contentededit을 했습니다.
문제는 제가 PHP로만 프로그래밍하는 방법을 알고 있다는 것입니다.저는 그것을 작동시키기 위해 몇 시간 동안 인터넷을 검색했지만, 그것을 작동시키기에 충분한 데이터를 저장하는 데 사용되는 프로그래밍 언어를 이해하지 못합니다.

다음과 같이 작동했으면 합니다.

  1. 는 'edit을 누릅니다.
  2. editable.div가 .
  3. '저장.
  4. 데이터는 파일 또는 데이터베이스에 저장됩니다(가장 좋은 옵션이 무엇인지 잘 모르겠습니다).
  5. 페이지가 열리면 편집된 내용이 나타납니다.

지금 내가 가진 건 이게 전부입니다.

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

관리자가 '편집'을 눌렀을 때 div를 만족할 수 있는 div로 변환하는 부분을 만드는 방법을 알고 있습니다.
저의 문제는 편집된 데이터를 저장하는 방법을 정말로 모른다는 것입니다.
데이터가 저장되는 방식에 따라 파일에서 데이터를 검색하는 것이 어려울지도 모르겠습니다.데이터베이스에 저장하면 검색하는 데 문제가 없겠지만, 가능한지, 최선의 방법인지는 모르겠습니다.

도와주셔서 고마워요.

사무엘


편집:

@초고속 답변 정말 감사합니다!
저는 그것을 작동시키려고 노력했지만, 아직 작동하지 않습니다.저는 제가 무엇을 잘못하고 있는지 알 수가 없어요.

내 코드는 다음과 같습니다.
과도한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:

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

당신의 큰 도움에 다시 한번 감사드립니다!
사용자가 버튼을 누를 때만 div를 편집할 수 있도록 도와줄 수 있습니까?


솔루션:

마침내 모든 것이 잘 되기까지 2주가 넘게 걸렸습니다.자바스크립트, jQuery, Ajax를 배워야 했습니다.하지만 지금은 완벽하게 작동합니다.나는 심지어 그 화려함을 위해 몇 가지 여분을 추가했습니다 :)
만약 누군가가 이것을 하기를 원한다면 저는 제가 어떻게 이것을 했는지 공유하고 싶습니다.

과도한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:
//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:
<?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>";
    }
?>

입력 상자를 편집할 수 있는지 여부를 관리하려면 JavaScript(또는 best, jQuery)와 같은 클라이언트 측 언어를 사용합니다.

AJAX를 사용하여 필드 데이터를 가져와 PHP 파일로 전송하면 데이터가 데이터베이스에 저장됩니다.

다음은 jQuery를 사용하여 입력 필드의 활성화/비활성화를 관리하는 매우 단순한 예입니다.

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 파일: some_php_file.php

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

AJAX를 사용하는 것은 매우 쉽습니다.저는 그것이 어떻게 보일지에 대한 아주 간단한 예를 제시했습니다.HTML 또는 jQuery에서 검색하지 마십시오.moreTxt변수 -- 아약스에 두 번째 변수를 추가하는 방법을 보여주기 위해 추가했습니다.

다음은 Ajax에 대한 최신 정보를 제공하기 위한 몇 가지 기본적인 예입니다.

JQuery를 사용한 AJAX 콜백 요청


jQuery나 AJAX를 배우는 데는 지름길이 없습니다.예제를 읽고 실험을 수행합니다.

다음 사이트에서 우수한 무료 jQuery 튜토리얼을 찾을 수 있습니다.

http://thenewboston.com

http://phpacademy.org


업데이트 편집:

귀하의 의견 문의에 답변하기 위해:

DIV에서 PHP 파일로 데이터를 전송하려면 먼저 코드를 트리거하는 이벤트가 필요합니다.당신이 언급했듯이, 입력 필드에서, 이것은 다음과 같을 수 있습니다.blur()이벤트 - 사용자가 필드를 떠날 때 트리거합니다.에서<select>그것이 될 수 있습니다.change()이벤트 - 선택 항목을 선택할 때 트리거합니다.하지만 DIV에서는... 음, 사용자는 DIV와 상호 작용할 수 없습니다, 그렇죠?트리거는 단추를 클릭하는 등 사용자가 수행하는 작업이어야 합니다.

합니다. -- 은 그서사용클릭다니합버튼을는래자를 하여 수 . 당신은 DIV의 내용을 얻을 수 있습니다..html() ( 및 에서는 명령을 합니다.).val()에서는 지만와테셀이사는합용니다야해서에하블을 사용해야 ..html()코드는 다음과 같습니다.

버튼 클릭 후 DIV 콘텐츠 전송 방법:

HTML:

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

jQuery:

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

});

다음을 사용하여 전체 페이지 클라이언트 측을 저장할 수 있습니다.

    <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

언급URL : https://stackoverflow.com/questions/25790268/how-to-save-and-retrieve-contenteditable-data

반응형