|
|
|
สอบถามวิธีกำหนดค่า HTML ที่ encode แล้วลงใน input หรือ textarea |
|
|
|
|
|
|
|
ต้อง decode ครับ เพราะใช้ htmlspecialchars()
และ ดูเหมือน echo ของ php มันจะ decode ระดับแรกให้แล้ว
Code (PHP)
<?php
$name = htmlspecialchars('<p>p</p>'); //1 level encoded
echo htmlspecialchars($name);
echo '<br>' . $name;
echo '<br><br>';
$name = htmlspecialchars(htmlspecialchars('<p>p</p>')); //2 level encoded
echo $name . '<br>';
echo htmlspecialchars_decode($name);
การ decode ในไฟล์ 2 ด้วย JavaScript
test02.php
<div id="saved-result-text" style="display:none;">
saved result: <span id="saved-result"></span>
</div>
<form id="saveForm" method="post">
<input id="name" type="text" name="name" value="" maxlength="50">
<br>
<button type="submit" onclick="return ajaxSave();">Save</button>
</form>
<p>Normal JS save/display.</p>
<script>
function ajaxSave() {
let formData = new FormData(document.getElementById('saveForm'));
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(this.response);
if (response.saved === true) {
window.location.reload();
}
}
};
xhr.open('POST', 'save.php');
xhr.send(formData);
return false;
}
// 1. DOM
/*
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
*/
// หรือ
// 2. RegEx
function decodeEntities(encodedString) {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {
"nbsp":" ",
"amp" : "&",
"quot": "\"",
"lt" : "<",
"gt" : ">"
};
return encodedString.replace(translate_re, function(match, entity) {
return translate[entity];
}).replace(/&#(\d+);/gi, function(match, numStr) {
var num = parseInt(numStr, 10);
return String.fromCharCode(num);
});
}
// หรือ 3. ใช้ library เสริม เช่น he
// https://github.com/mathiasbynens/he
// ฯลฯ
document.addEventListener('DOMContentLoaded', function() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(this.response);
if (response && response.name) {
document.getElementById('saved-result-text').style = '';
document.getElementById('saved-result').innerHTML = response.name;
//document.getElementById('name').value = decodeHtml(response.name);
document.getElementById('name').value = decodeEntities(response.name);
}
}
};
xhr.open('GET', 'save.php');
xhr.send();
return false;
}, false);
</script>
|
|
|
|
|
Date :
2020-05-14 00:42:24 |
By :
PhrayaDev |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 00
|