我正在嘗試根據從用戶那里獲得的資料創建一個 url。如果我們認為這是我的 url:
let url = new URL('http://localhost:8080/api/movies/search/search');
我添加這樣的搜索欄位:
for (let item in data) {
url.searchParams.set(item,data[item]);
}
但在我的網址末尾,我想添加排序型別,使其看起來像這樣:
const url = `http://localhost:8080/api/movies/search/search?title=something&minRate=10&genre=action&sort=title,asc`;
那么我應該如何用逗號添加最后一部分:
,asc
到網址?
uj5u.com熱心網友回復:
根據對上述問題的評論......
如果data是這樣:
{
title: 'the',
minRate: 2,
genre: 'action',
sortType: 'title',
type: 'asc'
}
你想要的結果是這樣的:
http://localhost:8080/api/movies/search/search?title=the&minRate=2&genre=action&sort=title,asc
然后data與您要查找的內容不匹配。它有兩個名為sortTypeand的屬性type,而您想要一個名為 的組合屬性sort。
將物件投影成您想要的形狀,然后使用該新物件來構建您的引數:
let data = {
title: 'the',
minRate: 2,
genre: 'action',
sortType: 'title',
type: 'asc'
};
let url = new URL('http://localhost:8080/api/movies/search/search');
// create the object you want:
let urlData = {
title: data.title,
minRate: data.minRate,
genre: data.genre,
sort: `${data.sortType},${data.type}`
};
// then add params from *that* object:
for (let item in urlData) {
url.searchParams.set(item, urlData[item]);
}
console.log(url);
(請注意,,默認情況下該字符是 URL 編碼的。)
基本上,不要改變邏輯來解決資料結構。保持邏輯簡單并將資料結構更改為您需要的結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517814.html
上一篇:AndroidStudio從URL中檢索檔案并決議內容
下一篇:根據條件過濾URL串列
