Ajax & JSON搜索代码中如何将res['state']转为小写连字符格式?
解决Ajax搜索代码中的URL格式转换问题
要实现将res["state"]转换为全小写且空格替换为连字符的需求,只需在原代码中对res["state"]调用两个字符串方法即可:
修改核心代码行:
将
line.innerHTML = `<a href='<?= $baseurl ?>/listings/${res["state"]}/${res["slug"]}'>${res["city_name"]}, ${res["state_name"]}</a>`;
替换为
line.innerHTML = `<a href='<?= $baseurl ?>/listings/${res["state"].toLowerCase().replace(/\s+/g, '-')}/${res["slug"]}'>${res["city_name"]}, ${res["state_name"]}</a>`;
完整修改后的函数代码
function ajsearch () { var data = new FormData(); data.append("search", document.getElementById("search").value); data.append("ajax", 1); fetch("2-search.php", { method:"POST", body:data }) .then(res => res.json()).then((results) => { var wrapper = document.getElementById("results"); if (results.length > 0) { wrapper.innerHTML = ""; for (let res of results) { let line = document.createElement("div"); line.innerHTML = `<a href='<?= $baseurl ?>/listings/${res["state"].toLowerCase().replace(/\s+/g, '-')}/${res["slug"]}'>${res["city_name"]}, ${res["state_name"]}</a>`; wrapper.appendChild(line); } } else { wrapper.innerHTML = "No city or town found request it be added by using our <a href='<?= $baseurl ?>/contact'><strong>contact form</strong></a>"; } }); return false; }
方法说明
- toLowerCase():将
res["state"]的所有字符转换为小写格式 - replace(/\s+/g, '-'):通过正则表达式匹配所有连续空格(
\s+),并全局替换为连字符-,确保所有空格都被替换,而非仅第一个
内容的提问来源于stack exchange,提问作者MrX
相关产品推荐
相关产品推荐

