我一直在試圖弄清楚如何在這個簡單的函數中使用ajax。Jquery AJAX - 單擊此按鈕時更新文本的範圍
我有一個跨度顯示用戶在其播放列表中有多少首歌曲。它只是顯示localStorage密鑰內存在多少個值。
<span id="count-songs-span">
<script>
var countSongs = JSON.parse(localStorage.playlist).length;
document.write(countSongs);
</script>
</span>
我們使用jPlayer,我們有一個播放列表設置。當您從播放列表中刪除歌曲(通過單擊刪除按鈕)時,我們希望用新的記數更新該「div-count-songs-span」的div內容。目前,它只在刷新頁面時才起作用,但我們希望使用ajax進行更新。
我們增加了一個點擊事件刪除按鈕的位置:
$('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
window.setTimeout(updatePlaylist, 500);
});
updatePlaylist()如下:
function updatePlaylist(){
playlist = myPlaylist.playlist;
storage.set('playlist', playlist);
}
的單擊事件保存列表localStorage的,這很好。但在此之前,我們想用ajax更新countSongs變量。
我從另一個網站上看到了這個代碼片段,並且試圖將它適應到我的網站,但是我無法讓它正常工作。這只是我的網站的正確的代碼。
$.ajax({
type : "get",
dataType : "json",
url : ajax_object.ajaxurl,
data : {action: "get_media", id : id},
success: function(obj) {
if(obj.length == 1){
player.add(obj[0], true);
updatePlaylist();
}else if(obj.length > 1){
player.setPlaylist(obj);
player.play(0);
updatePlaylist();
}
}
});
任何人都可以幫助我使用ajax來更新「count-songs-span」嗎?
非常感謝,如果你可以幫忙。
UPDATE:
這裏是存儲什麼的演示。
存儲播放列表數據的方法:
function updatePlaylist(){
playlist = myPlaylist.playlist;
storage.set('playlist', playlist);
}
任何地方,我們需要存儲的播放列表信息,我們稱之爲方法 - updatePlaylist()
這是被存儲什麼是一個例子:
[{"title":"Mauvais Temps","artist":"Right Beat Radio","mp3":"/mp3s/MauvaisTemps.mp3"},{"title":"Line Steppers","artist":"Right Beat Radio","mp3":"/mp3s/LineSteppers.mp3"},{"title":"Try My Best","artist":"Right Beat Radio","mp3":"/mp3s/TryMyBest.mp3"},{"title":"San Ignacio","artist":"Right Beat Radio","mp3":"/mp3s/SanIgnacio.mp3"}]
所以,當我們要計算在播放列表中的歌曲數量,我們使用這個(在localStorage的密鑰被稱爲「播放列表」:
var countSongs = JSON.parse(localStorage.playlist).length;
document.write(countSongs);
更新#2:
截圖:
https://rightbeatradio.com/wp-content/uploads/2015/09/Screen-Shot-2015-09-07-at-9.13.34-AM.png
希望這個截圖會有所幫助。您可以在那裏看到播放列表,在上面可以看到當前列表中的歌曲數量(7首歌曲)。
除了名單上的每首歌曲,有一個刪除(X)按鈕。此按鈕允許用戶從列表中刪除歌曲。
當點擊該按鈕,這些功能火:
//Remove Item from Playlist
$('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
window.setTimeout(updatePlaylist, 500);
});
// update playlist
function updatePlaylist(){
playlist = myPlaylist.playlist;
storage.set('playlist', playlist);
}
某處在那裏,我們想也算項目在本地存儲,「播放」鍵的數量,並通過更新計數阿賈克斯。
下面是計算在播放列表中的歌曲數量跨度的HTML:
<span id="count-songs-span">
<script>
var countSongs = JSON.parse(localStorage.playlist).length;
document.write(countSongs);
</script>
</span>
該腳本被調用的唯一情況是,當我們刷新頁面。我們希望在單擊remove按鈕時調用countSongs腳本,並使用ajax更新該範圍內的計數。
您正在更新本地存儲數據嗎? – Rayon
是的,在刪除按鈕「jp-playlist-item-remove」的點擊事件中,我們正在更新localStorage。我已經添加了上面的存儲方法。 – anthonyCam
你能否提供帶有虛擬數據的小型演示? – Rayon