[英]TinyMCE 4: Get text area content to send with Axios
我正在進行一些測試,試圖獲取TinyMCE 4
呈現的textarea
的內容,以通過Axios
在post request
發送它,但我無法做到。
我嘗試使用document.getElementById
和tinymce.get('mytextarea')
但這些都tinymce.get('mytextarea')
。
document.getElementById
返回一個空字符串tinymce.get('mytextarea')
返回 null這是我的代碼:
<!DOCTYPE html>
<html>
<head>
<title>Two Forms</title>
<script src='https://cloud.tinymce.com/stable/tinymce.min.js'></script>
<script>
let editor = tinymce.init({
selector: '#mytextarea',
});
//Line to test if get function works. But it dosen't work console excepction
//Uncaught TypeError: Cannot read property 'setContent' of null
tinymce.get('mytextarea').setContent('Hello');
</script>
</head>
<body>
<form action="post.php" method="post">
<textarea id="mytextarea" name="body"></textarea>
<input type="submit" name="input" value="POST">
<button onclick="send()" type="button">GET</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js" integrity="sha512-DZqqY3PiOvTP9HkjIWgjO6ouCbq+dxqWoJZ/Q+zPYNHmlnI2dQnbJ5bxAHpAMw+LXRm4D72EIRXzvcHQtE8/VQ==" crossorigin="anonymous"></script>
<script type="text/javascript">
//Trying to get the text area value but it dosen't work neither. returns an empty string
//let body = document.getElementById('mytextarea').value;
//Try to get the text area content to store in body variable, returns null
let body = tinymce.get('mytextarea');
function send() {
console.log('The Body: ' + body);
axios.post('/post.php', {
body: body
})
.then((response) => {
console.log(response.data);
}, (error) => {
console.log(error);
});
}
</script>
</body>
</html>
post.php
只有這個內容來處理請求。
<?php
//Takes the post from the form.
if (isset($_POST['body'])) {
echo "POST " . $_POST['body'];
} else {
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
var_dump($data->body);
}
注意:僅用於測試目的,我使用了 2 個按鈕,用於正常發送表單的input
和通過Axios
發送帖子的button
當您加載 TinyMCE 時,您將使用iframe
覆蓋原始textarea
。 如果您不使用本機表單提交過程,則需要手動...
getContent()
API 從 TinyMCE 中提取數據triggerSave()
API 獲取 TinyMCE 以更新textarea
在調用send()
函數之前,只需調用以下內容:
tinymce.triggerSave();
...應該導致 TinyMCE 更新底層textarea
。
注意:在您當前的代碼中,您調用let body = tinymce.get('mytextarea');
. 這只是將body
變量分配給瀏覽器中 TinyMCE 對象的引用,而不是編輯器的內容。 這需要像let body = tinymce.get('mytextarea').getContent();
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.