javascript
Spring Boot中带有CKEditor的AJAX
1.概述
在本文中,我們將介紹如何在Spring Boot中使用CKEditor 。 在本教程中,我們將導入一個包含大量數據的XML文檔,對使用GET請求將一組數據加載到CKEditor實例的能力進行編程,并執行POST請求以保存CKEditor的數據。
我們將使用的技術包括MongoDB,Thymeleaf和Spring Batch。
Github上提供了本教程的完整源代碼。
2.什么是CKEditor?
CKEditor是一個基于瀏覽器的“所見即所得”(WYSIWYG)內容編輯器 。 CKEditor旨在將Web編輯器(如Microsoft Word和OpenOffice)中常見的文字處理器功能引入Web界面。
CKEditor在用戶界面,插入內容,創作內容等方面為最終用戶提供了許多功能。
有不同版本的CKEditor,但在本教程中,我們使用CKEditor4。要查看演示,請訪問: https : //ckeditor.com/ckeditor-4/
3. XML文檔
如前所述,我們正在此應用程序中上載XML文檔。 XML數據將被插入數據庫,并在本教程的其余部分中使用。
<?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.型號
對于上面的XML代碼,我們可以像這樣對Song進行建模:
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 + "]";}}對于我們的應用程序,我們將區分未修改的歌曲和在CKEditor中使用單獨的模型和存儲庫修改過的歌曲。
現在讓我們定義什么是更新的歌曲:
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.文件上傳和處理
由于本文的重點是CKEditor和AJAX,因此我們不會詳細介紹使用Spring Batch進行文件上傳和處理。 我們在之前的帖子中對這個過程進行了深入的審查,但是:
- Spring批處理CSV處理
- 在MongoDB中將XML轉換為JSON +原始使用+ Spring Batch
6.將數據設置為CKEditor – GET請求
我們的目標是檢索單個歌曲的數據并在CKEditor中顯示該數據。 有兩個問題要解決:檢索單個歌曲的數據并將其顯示在CKEditor中。
6.1客戶端代碼
在view.html中,我們使用Thymeleaf中的一個表來迭代 Song存儲庫中的每首 Song。 為了能夠從服務器檢索特定歌曲的數據,我們將Song的ID傳遞給函數。
這是負責調用從服務器檢索數據并隨后將數據設置為CKEditor實例的函數的代碼片段:
<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對于我們能夠檢索數據至關重要。
在getSong函數中,我們使用延遲的Promise來確保在GET請求之后設置數據 :
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服務器端代碼
getSong接受一個名為sid的參數,該參數代表Song id。 sid也是@GetMapping中的路徑變量。 我們將sid視為字符串,因為這是MongoDB中Song的ID 。
我們檢查Song是否已被修改,如果是,我們將檢索關聯的UpdatedSong實體。 如果沒有,我們將以不同的方式對待這首歌。 最終,我們返回一個帶有String的簡單POJO,用于名為ResponseModel的數據:
@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是一個非常簡單的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數據– POST請求
發布數據并不是很大的挑戰。 但是,可以確保正確處理數據。
7.1客戶端代碼
由于CKEditor實例是表單中的文本區域,因此我們可以觸發表單提交上的函數:
$(document) .ready( function() {// SUBMIT FORM $("#form").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); ajaxPost(); });ajaxPost()在CKEditor中檢索當前數據,并將其設置為變量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是“文本”
內容類型或數據類型不正確會導致錯誤或數據格式錯誤。
7.2服務器端代碼
我們在POST請求的contentType中聲明媒體類型為“ text / html” 。 我們需要在映射中指定將使用此映射。 因此,我們在@PostMapping中添加消耗= MediaType.TEXT_HTML_VALUE 。
我們需要注意的領域包括:
- @RequestBody字符串主體負責將變量主體設置為我們請求的內容
- 我們再次返回ResponseModel ,它是前面描述的包含數據的簡單POJO
- 我們將先前修改過的SongModel與之前未修改過的SongModel區別對待
同樣,像GET請求一樣, 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.演示
我們訪問localhost:8080 :
我們上傳提供的music-example.xml文件:
我們單擊“加載”以查看歌曲:
我們添加內容,然后單擊“保存”:
如果返回保存的內容,則換行符可能會顯示“ \ n”。 目前,對此進行討論超出了本教程的范圍。
9.結論
在本教程中,我們介紹了如何使用帶有對象ID的GET請求加載數據,如何將數據設置為CKEditor實例以及如何通過POST請求將CKEditor的數據保存回數據庫。 還有一些額外的代碼,例如不必為數據使用兩個不同的實體(原始版本和修改版本),但這希望是有啟發性的。
完整的代碼可以在Github上找到。
翻譯自: https://www.javacodegeeks.com/2017/11/ajax-ckeditor-spring-boot.html
總結
以上是生活随笔為你收集整理的Spring Boot中带有CKEditor的AJAX的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 教育部学历认证电子注册备案表英文版(教育
- 下一篇: drools 决策表_骆驼和春天的Dro