EOND
HOSTING
WEBDeveloper
FreelancerCafe
Threads

1. list.blade.php

@if($document->isEditable()) <form action="javascript:void(0);" method="post" class="toggle-secret-form" data-documentsrl="{$document->document_srl}"> <input type="hidden" name="document_srl" value="{$document->document_srl}" /> @if(!$document->isSecret()) <input type="hidden" name="status" value="SECRET"> <button type="submit">스레드 잠금 <i class="lock"></i></button> @else <input type="hidden" name="status" value="PUBLIC"> <button type="submit">잠금 해제하기</button> @endif <input type="hidden" name="xe_validator_id" value="{$_SESSION['XE_VALIDATOR_ID']}"> </form> @php // 비밀글 전환 처리 if ($_POST['status'] == 'SECRET' && isset($_POST['document_srl'])) { $obj = new stdClass(); $obj->document_srl = $_POST['document_srl']; $obj->secret = 'SECRET'; // status를 'SECRET'으로 설정 $query_path = $module_info->module."/skins/".$module_info->skin; // 쿼리 경로 $output = executeQuery($query_path.'.updateDocumentsSecret', $obj); // 쿼리 실행 } // 공개글 전환 처리 if ($_POST['status'] == 'PUBLIC' && isset($_POST['document_srl'])) { $obj = new stdClass(); $obj->document_srl = $_POST['document_srl']; $obj->secret = 'PUBLIC'; // status를 'PUBLIC'으로 설정 $query_path = $module_info->module."/skins/".$module_info->skin; // 쿼리 경로 $output = executeQuery($query_path.'.updateDocumentsSecret', $obj); // 쿼리 실행 // 페이지 리다이렉트 (새로고침 효과) } @endphp


2. script.js

document.querySelectorAll(".toggle-secret-form").forEach(function(form) { console.log('폼 감지됨'); // ✅ 폼이 감지되었는지 확인 form.addEventListener("submit", function(e) { console.log('비밀글 처리 이벤트 발생'); // ✅ 이벤트 바인딩 확인 e.preventDefault(); // 기본 폼 제출 방지 let formData = new FormData(this); let documentSrl = this.dataset.documentsrl; // CSRF 토큰 추가 (필요하면 설정) if (typeof XE_VALIDATOR_ID !== "undefined") { formData.append("xe_validator_id", XE_VALIDATOR_ID); } fetch("./", { method: "POST", body: formData }) .then(function(response) { // ✅ 올바른 문법 window.location.reload(); // 페이지 새로고침 }) .catch(error => console.error("Error:", error)); }); });



#업데이트(2025-02-15)

리스트에서 바로 비밀글로 변경하는 팁입니다. 사용하면서 2가지 문제가 발견되어 포스팅합니다.


(1) 레디스를 사용할 경우 비밀글 전환이 안되는 문제


첫번째 문제는 원인을 알 수 없이(늘 그렇듯이) 리스트에서 글상태 변경이 안되는 문제가 발견되었습니다.

로컬호스트에서 작업할 때는 정상적으로 비밀글/일반글 전환이 잘 되었는데 실 서버에 업로드한 뒤에 해당 현상이 발견되었습니다.


해당 문제의 원인은 redis 서버 캐시를 사용할 경우 redis 캐시에서 해당 글 상태가 바로 업데이트 되지 않아 발생했던 문제였습니다.


$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->select(2);
// 문서 번호
$document_srl = $_POST['document_srl'];

// 문서 번호 관련 키 찾기 (KEYS 명령어 사용)
$keys = $redis->keys("*$document_srl");

// 키가 존재하면 삭제
if (!empty($keys)) {
    foreach ($keys as $key) {
       $redis->del($key);  // 해당 키 삭제
    }
    //echo "관련 캐시 키 삭제 완료!";
} else {
    //echo "해당 문서의 캐시 키를 찾을 수 없습니다.";
}


redis 포트, redis DB 번호를 적어주고,

해당 키를 삭제해주는 방식으로 해결했습니다.


어떤 캐시 방법을 사용하는지는 아래 팁으로 체크할 수 있습니다.

https://eond.com/xe/473539



(2) 리스트에서 비밀글 변경 후 글보기로 이동되는 문제


두번째 발생한 문제는 또 잘 동작이 됐었는데 어느 순간 동작이 안되어서 확인해보니 작성한 스크립트를 정리 중에 잘못 적어 발생했던 문제였습니다. ㅠㅠ


document.querySelectorAll(".toggle-secret-form").forEach(function(form) {
    form.addEventListener("submit", function(e) {
       e.preventDefault(); // 기본 폼 제출 방지

       let formData = new FormData(this);
       let documentSrl = this.dataset.documentsrl;
       // CSRF 토큰 추가 (필요하면 설정)
       // meta 태그에서 CSRF 토큰을 가져옴
       const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

       // CSRF 토큰이 있을 때만 실행
       if (csrfToken) {
          // 이후 fetch 요청 시 CSRF 토큰을 포함
          formData.append("xe_validator_id", csrfToken);
          console.error(csrfToken);
       } else {
          console.error("CSRF 토큰이 없습니다.");
       }
       fetch(form.action, {
          method: "POST",
          body: formData,
          // credentials: "include" // 인증 쿠키 포함 (중요)
       })
          .then(function(response) {  // ✅ 올바른 문법
             // console.log('페이지 새로고침');
             window.location.reload(); // 페이지 새로고침
          })
          .catch(error => console.error("Error:", error));
    });
});


해당 코드의 셀렉터를 잘못 입력해서 정상적으로 해당 스크립트를 불러오지 못하고 있었네요.

 


Type something
0
댓글은 로그인 사용자만 작성 가능합니다. 로그인하기