最近在迭代一個(gè)前后端不分離的老項(xiàng)目,jsp語(yǔ)法對(duì)于一個(gè)前端新手總是顯得不是很友好的廓握,畢竟寫html和js代碼多了以后供常,在更改jsp代碼的時(shí)候會(huì)有一些不適應(yīng),比如在ajax獲取請(qǐng)求并且使用jquery和ES6渲染頁(yè)面的時(shí)候晦炊,jsp的EL模板和ES6的拼接字符串都用到了${}這個(gè)表達(dá)式:
<script>
$.ajax({
//請(qǐng)求方式
type : "POST",
//請(qǐng)求的媒體類型
header:"Access-Control-Allow-Origin:*",
contentType: "application/json;charset=UTF-8",
//請(qǐng)求地址
url : "credit/new",
//數(shù)據(jù),json字符串
data : "data",
//請(qǐng)求成功
success : function(result) {
var _result = JSON.parse(result);
// console.log("........",_result);
var arr = _result.data;
// console.log("arr",arr);
console.log(date)
for (var i = 0;i < 4;i++){
console.log("4ge",arr[i])
var date = new Date(arr[i].publishDate).toLocaleString().slice(0,10).replace(/\//g,"-").replace("-","0");
var year = date.slice(0,4);
var day = date.slice(4)
console.log("shijian",year)
console.log("tianshu",day)
var node = $(`
<a href="${home}credit_detail/?${'${arr[i].id}'}" target="_blank" class="lh_credit_news_link_box">
<div class="lh_credit_news_link_date">
<p class="lh_credit_link_date_day">${'${day}'}</p>
<p class="lh_credit_link_date_year">${'${year}'}</p>
</div>
<div class="lh_credit_news_link_content">
<p class="lh_credit_news_link_content_title">${'${arr[i].bt}'}</p>
<p class="lh_credit_news_link_content_summary">${'${arr[i].zhy}'}</p>
</div>
</a>
`)
node.appendTo('#lh_credit_news_link');
}
},
//請(qǐng)求失敗宁脊,包含具體的錯(cuò)誤信息
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
})
</script>
這一段代碼本身我分離出一個(gè)單獨(dú)的js去寫的断国,在解析這段代碼時(shí)出現(xiàn)了問題:
var node = $(`
<a href="${home}credit_detail/?${arr[i].id}" target="_blank" class="lh_credit_news_link_box">
<div class="lh_credit_news_link_date">
<p class="lh_credit_link_date_day">${day}</p>
<p class="lh_credit_link_date_year">${year}</p>
</div>
<div class="lh_credit_news_link_content">
<p class="lh_credit_news_link_content_title">${arr[i].bt}</p>
<p class="lh_credit_news_link_content_summary">${arr[i].zhy}</p>
</div>
</a>
`)
因?yàn)?{home}是el表達(dá)式而其他的,其他的是ES6的模板語(yǔ)法,遇到這個(gè)問題怎么解決呢榆苞?
直接將這個(gè)ajax的代碼寫在jsp文件中稳衬,并將要插入的節(jié)點(diǎn)中的es6模板語(yǔ)法作為字符串傳給el模板!
var node = $(`
<a href="${home}credit_detail/?${'${arr[i].id}'}" target="_blank" class="lh_credit_news_link_box">
<div class="lh_credit_news_link_date">
<p class="lh_credit_link_date_day">${'${day}'}</p>
<p class="lh_credit_link_date_year">${'${year}'}</p>
</div>
<div class="lh_credit_news_link_content">
<p class="lh_credit_news_link_content_title">${'${arr[i].bt}'}</p>
<p class="lh_credit_news_link_content_summary">${'${arr[i].zhy}'}</p>
</div>
</a>
`)
這樣就可以在jsp文件中完美使用ajax獲取后端數(shù)據(jù)并渲染頁(yè)面了~~