我正在嘗試建立一個 Spotify 請求系統,使用者可以在其中輸入歌曲名稱和藝術家。然後 API 傳回結果,使用者可以根據結果選擇正確的曲目並將其新增至 Spotify 佇列。我已經包含了 CSS/HTML 和 JS(減去授權程式碼)。
HTML
`
<label for="song">Song Title:</label> <input type="text"> <p><br> `</p> <p><strong>CSS</strong></p> <p>`body {<br> font-family: Arial, sans-serif;<br> margin: 0;<br> padding: 0;<br> background-image: url('Image preview.png');<br> background-size: contain; /* Ensures the image fits within the browser window <em>/<br> background-repeat: no-repeat; /</em> Prevents the image from repeating <em>/<br> background-position: center; /</em> Centers the image on the page <em>/<br> background-attachment: fixed; /</em> Ensures the background stays fixed while scrolling */<br> display: flex;<br> justify-content: center;<br> align-items: center;<br> height: 100vh;<br> }</p> <h2> results { </h2> <p>margin-top: 20px;<br> }</p> <p>.track {<br> padding: 10px;<br> border: 1px solid #ddd;<br> cursor: pointer;<br> margin-bottom: 5px;<br> }</p> <p>.track:hover {<br> background-color: #f9f9f9;<br> }</p> <p>.request {<br> text-align: center;<br> background-color: rgba(255, 255, 255, 0.8); /* Semi-transparent background */<br> padding: 20px;<br> border-radius: 10px;<br> box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);<br> width: 80%;<br> max-width: 500px;<br> }</p> <p>.songSearchForm {<br> margin: auto;<br> width: 100%;<br> padding: 10px;<br> }</p> <p>h1 {<br> margin-bottom: 20px;<br> }</p> <p>form {<br> display: flex;<br> flex-direction: column;<br> gap: 10px;<br> }</p> <p>label, input, button {<br> margin: 5px 0;<br> }<br> `</p> <p><strong>JS</strong></p> <p>`const token = 'MY-ACCESS-TOKEN'; // Replace with your new access token</p> <p>document.getElementById('songSearchForm').addEventListener('submit', function(e) { <br> e.preventDefault(); </p> <pre class="brush:php;toolbar:false">const artist = document.getElementById('artist').value; const song = document.getElementById('song').value; const query = `track:${song} artist:${artist}`; fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track`, { headers: { 'Authorization': `Bearer ${token}`
}
})
.then(回應 => {
if (!response.ok) {
拋出新錯誤(HTTP 錯誤!狀態:${response.status});
}
返回response.json();
})
.then(數據 => {
const searchResultsDiv = document.getElementById('searchResults');
searchResultsDiv.innerHTML = data.tracks.items.map(track =>
document.getElementById('addToQueue').addEventListener('click', function() {
const selectedTrack = document.querySelector('input[name="track"]:checked').value;
console.log(選定的曲目 URI: ${selectedTrack});
fetch(https://api.spotify.com/v1/me/player/queue?uri=${selectedTrack}, {
方法:'POST',
標題:{
「授權」:不記名${token}
}
})
.then(回應 => {
console.log('API 回應:', 回應); // 記錄整個回應
if (!response.ok) {
拋出新錯誤(HTTP 錯誤!狀態:${response.status});
}
返回response.json();
})
.then(數據 => {
console.log('軌跡已加入佇列!', data);
})
.catch(error => console.error('將曲目加入佇列時發生錯誤:', error));
});`
有人可以檢查我的編碼是否正確,因為它不起作用
以上是需要幫助!的詳細內容。更多資訊請關注PHP中文網其他相關文章!