javascript
ckeditor回显带标签_Spring Boot中带有CKEditor的AJAX
ckeditor回顯帶標(biāo)簽
1.概述
在本文中,我們將介紹如何在Spring Boot中使用CKEditor 。 在本教程中,我們將導(dǎo)入一個(gè)包含大量數(shù)據(jù)的XML文檔,對(duì)使用GET請(qǐng)求將一組數(shù)據(jù)加載到CKEditor實(shí)例的能力進(jìn)行編程,并執(zhí)行POST請(qǐng)求以保存CKEditor的數(shù)據(jù)。
我們將使用的技術(shù)包括MongoDB,Thymeleaf和Spring Batch。
Github上提供了本教程的完整源代碼。
2.什么是CKEditor?
CKEditor是一個(gè)基于瀏覽器的“所見即所得”(WYSIWYG)內(nèi)容編輯器 。 CKEditor旨在將Web編輯器(如Microsoft Word和OpenOffice)中常見的文字處理器功能引入Web界面。
CKEditor在用戶界面,插入內(nèi)容,創(chuàng)作內(nèi)容等方面為最終用戶提供了眾多功能。
有不同版本的CKEditor,但是在本教程中,我們使用的是CKEditor4。要查看演示,請(qǐng)?jiān)L問: https : //ckeditor.com/ckeditor-4/
3. XML文檔
如前所述,我們正在此應(yīng)用程序中上載XML文檔。 XML數(shù)據(jù)將被插入數(shù)據(jù)庫(kù),并在本教程的其余部分中使用。
<?xml version="1.0"?> <Music xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="MUS-1" style="1.1"> <status date="2017-11-07">draft</status><title xmlns:xhtml="http://www.w3.org/1999/xhtml" >Guide to Music I Like - No Specific Genre</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >This guide presents a catalog of music that can be found on Spotify. <html:br xmlns:html="http://www.w3.org/1999/xhtml"/><html:br xmlns:html="http://www.w3.org/1999/xhtml"/>This is a very small sample of music found on Spotify and is no way to be considered comprehensive.</description><songs><song><artist>Run the Jewels</artist><song-title>Legend Has It</song-title></song><song><artist>Kendrick Lamar</artist><song-title>ELEMENT.</song-title></song><song><artist>Weird Al Yankovic</artist><song-title>NOW That's What I Call Polka!</song-title></song><song><artist>Eiffel 65</artist><song-title>Blue (Da Ba Dee) - DJ Ponte Ice Pop Radio</song-title></song><song><artist>YTCracker</artist><song-title>Hacker Music</song-title></song><song><artist>MAN WITH A MISSION</artist><song-title>Raise Your Flag</song-title></song><song><artist>GZA, Method Man</artist><song-title>Shadowboxin'</song-title></song></songs> </Music>4.型號(hào)
對(duì)于上面的XML代碼,我們可以像這樣對(duì)Song進(jìn)行建模:
public class SongModel {@Idprivate String id;@Indexedprivate String artist;@Indexedprivate String songTitle;@Indexedprivate Boolean updated;public Boolean getUpdated() {return updated;}public void setUpdated(Boolean updated) {this.updated = updated;}public String getArtist() {return artist;}public void setArtist(String artist) {this.artist = artist;}public String getSongTitle() {return songTitle;}public void setSongTitle(String songTitle) {this.songTitle = songTitle;}public String getId() {return id;}public void setId(String id) {this.id = id;}@JsonCreatorpublic SongModel(@JsonProperty("artist") String artist,@JsonProperty("song-title") String songTitle){this.artist = artist;this.songTitle = songTitle;}@Overridepublic String toString() {return "Person [id=" + id + ", artist=" + artist + ", song-title=" + songTitle + "]";}}對(duì)于我們的應(yīng)用程序,我們將區(qū)分未修改的歌曲和在CKEditor中使用單獨(dú)的模型和存儲(chǔ)庫(kù)修改過的歌曲。
現(xiàn)在讓我們定義什么是更新的歌曲:
public class UpdatedSong {@Idprivate String id;@Indexedprivate String artist;@Indexedprivate String songTitle;@Indexedprivate String html;@Indexedprivate String sid;public String getSid() {return sid;}public void setSid(String sid) {this.sid = sid;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getArtist() {return artist;}public void setArtist(String artist) {this.artist = artist;}public String getSongTitle() {return songTitle;}public void setSongTitle(String songTitle) {this.songTitle = songTitle;}public String getHtml() {return html;}public void setHtml(String html) {this.html = html;}}5.文件上傳和處理
由于本文的重點(diǎn)是CKEditor和AJAX,因此我們不會(huì)詳細(xì)介紹使用Spring Batch進(jìn)行文件上傳和處理。 我們?cè)谥暗奶又袑?duì)這個(gè)過程進(jìn)行了深入的審查,但是:
- Spring批處理CSV處理
- 在MongoDB中將XML轉(zhuǎn)換為JSON +原始使用+ Spring Batch
6.將數(shù)據(jù)設(shè)置為CKEditor – GET請(qǐng)求
我們的目標(biāo)是檢索單個(gè)歌曲的數(shù)據(jù)并在CKEditor中顯示該數(shù)據(jù)。 有兩個(gè)問題要解決:檢索單個(gè)歌曲的數(shù)據(jù)并將其顯示在CKEditor中。
6.1客戶端代碼
在view.html中,我們使用Thymeleaf中的一個(gè)表來迭代 Song存儲(chǔ)庫(kù)中的每首 Song。 為了能夠從服務(wù)器檢索特定歌曲的數(shù)據(jù),我們將歌曲的ID傳遞給函數(shù)。
這是負(fù)責(zé)調(diào)用從服務(wù)器檢索數(shù)據(jù)并隨后將數(shù)據(jù)設(shè)置為CKEditor實(shí)例的函數(shù)的代碼片段:
<table class="table datatable"> <thead> <tr> <th>Artist</th> <th>Song Title</th> <th>Load</th> </tr> </thead> <tbody> <tr th:each="songList : ${songList}"> <td th:text="${songList.artist}">Text ...</td> <td th:text="${songList.songTitle}">Text ...</td> <td><button th:onclick="|getSong('${songList.id}')|" id="button" class="btn btn-primary btn-condensed"> <i class="glyphicon glyphicon-folder-open"></i> </button></td> </tr> </tbody> </table>如我們所見, Song的id對(duì)于我們能夠檢索數(shù)據(jù)至關(guān)重要。
在getSong函數(shù)中,我們使用延遲的Promise來確保在GET請(qǐng)求之后設(shè)置數(shù)據(jù) :
function getSong(song) {$.ajax({url : "/api/show/?sid=" + song,type : 'GET',dataType : 'text'}).then(function(data) {var length = data.length-2;var datacut = data.slice(9,length);CKEDITOR.instances.content.setData(datacut);});$("#form").attr("action", "/api/save/?sid=" + song);};6.2服務(wù)器端代碼
getSong接受一個(gè)名為sid的參數(shù),該參數(shù)代表Song id。 sid也是@GetMapping中的路徑變量。 我們將sid視為String,因?yàn)檫@是MongoDB中Song的ID 。
我們檢查Song是否已被修改,如果是,我們將檢索關(guān)聯(lián)的UpdatedSong實(shí)體。 如果沒有,我們將以不同的方式對(duì)待這首歌。 最后,我們?yōu)槊麨镽esponseModel的數(shù)據(jù)返回一個(gè)帶有字符串的簡(jiǎn)單POJO:
@GetMapping(value={"/show/","/show/{sid}"}) public ResponseEntity<?> getSong(@RequestParam String sid, Model model){ResponseModel response = new ResponseModel();System.out.println("SID :::::" + sid);ArrayList<String> musicText = new ArrayList<String>();if(sid!=null){String sidString = sid;SongModel songModel = songDAO.findOne(sidString);System.out.println("get status of boolean during get ::::::" + songModel.getUpdated());if(songModel.getUpdated()==false ){musicText.add(songModel.getArtist());musicText.add(songModel.getSongTitle());String filterText = format.changeJsonToHTML(musicText);response.setData(filterText);} else if(songModel.getUpdated()==true){UpdatedSong updated = updatedDAO.findBysid(sidString);String text = updated.getHtml();System.out.println("getting the updated text ::::::::" + text);response.setData(text);}}model.addAttribute("response", response);return ResponseEntity.ok(response); }ResponseModel是一個(gè)非常簡(jiǎn)單的POJO,如上所述:
public class ResponseModel {private String data;public ResponseModel(){}public ResponseModel(String data){this.data = data;}public String getData() {return data;}public void setData(String data) {this.data = data;} }7.保存CKEditor數(shù)據(jù)– POST請(qǐng)求
發(fā)布數(shù)據(jù)并不是很大的挑戰(zhàn)。 但是,可以確保正確處理數(shù)據(jù)。
7.1客戶端代碼
由于CKEditor實(shí)例是表單中的文本區(qū)域,因此我們可以觸發(fā)表單提交上的函數(shù):
$(document) .ready( function() {// SUBMIT FORM $("#form").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); ajaxPost(); });ajaxPost()在CKEditor中檢索當(dāng)前數(shù)據(jù),并將其設(shè)置為變量formData :
function ajaxPost() {// PREPARE FORM DATA var formData = CKEDITOR.instances.content .getData();// DO POST $ .ajax({ type : "POST", contentType : "text/html", url : $("#form").attr("action"), data : formData, dataType : 'text', success : function(result) {$("#postResultDiv") .html( "" + "Post Successfully! " + "");console.log(result); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } });}})重要的是要注意:
- contentType是“ text / html”
- dataType是“文本”
內(nèi)容類型或數(shù)據(jù)類型不正確會(huì)導(dǎo)致錯(cuò)誤或數(shù)據(jù)格式錯(cuò)誤。
7.2服務(wù)器端代碼
我們?cè)赑OST請(qǐng)求的contentType中聲明媒體類型為“ text / html” 。 我們需要在映射中指定將使用此映射。 因此,我們?cè)?#64;PostMapping上添加消耗= MediaType.TEXT_HTML_VALUE 。
我們需要注意的領(lǐng)域包括:
- @RequestBody字符串主體負(fù)責(zé)將變量主體設(shè)置為我們請(qǐng)求的內(nèi)容
- 我們?cè)俅畏祷豏esponseModel ,它是前面描述的包含數(shù)據(jù)的簡(jiǎn)單POJO
- 我們將先前修改過的SongModel與之前未修改過的SongModel區(qū)別對(duì)待
同樣,像GET請(qǐng)求一樣, sid允許我們處理正確的Song:
@PostMapping(value={"/save/","/save/[sid]"}, consumes = MediaType.TEXT_HTML_VALUE)public @ResponseBody ResponseModel saveSong( @RequestBody String body, @RequestParam String sid){ResponseModel response = new ResponseModel();response.setData(body);SongModel oldSong = songDAO.findOne(sid);String songTitle = oldSong.getSongTitle();String artistName = oldSong.getArtist();if(oldSong.getUpdated() == false){UpdatedSong updatedSong = new UpdatedSong();updatedSong.setArtist(artistName);updatedSong.setSongTitle(songTitle);updatedSong.setHtml(body);updatedSong.setSid(sid);oldSong.setUpdated(true);songDAO.save(oldSong);updatedDAO.insert(updatedSong);System.out.println("get status of boolean during post :::::" + oldSong.getUpdated());}else{UpdatedSong currentSong = updatedDAO.findBysid(sid);currentSong.setHtml(body);updatedDAO.save(currentSong);} return response;}8.演示
我們?cè)L問localhost:8080 :
我們上傳提供的music-example.xml文件:
我們單擊“加載”以查看歌曲:
我們添加內(nèi)容,然后單擊“保存”:
如果返回到保存的內(nèi)容,則換行符可能會(huì)顯示“ \ n”。 目前,對(duì)此進(jìn)行討論超出了本教程的范圍。
9.結(jié)論
在本教程中,我們介紹了如何使用帶有對(duì)象ID的GET請(qǐng)求加載數(shù)據(jù),如何將數(shù)據(jù)設(shè)置為CKEditor實(shí)例以及如何通過POST請(qǐng)求將CKEditor的數(shù)據(jù)保存回?cái)?shù)據(jù)庫(kù)。 還有一些額外的代碼,例如不必為數(shù)據(jù)使用兩個(gè)不同的實(shí)體(原始版本和修改版本),但這希望是有啟發(fā)性的。
完整的代碼可以在Github上找到。
翻譯自: https://www.javacodegeeks.com/2017/11/ajax-ckeditor-spring-boot.html
ckeditor回顯帶標(biāo)簽
總結(jié)
以上是生活随笔為你收集整理的ckeditor回显带标签_Spring Boot中带有CKEditor的AJAX的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 沿路疾驰的玩具车!Blender几何节点
- 下一篇: 品牌电脑和组装电脑的区别品牌电脑和组装电