因为首页对页面动态交互的需求比其他页面更大,所以这里使用JS与后台进行Ajax交互,并从后台拿到Json数据对其进行处理。
代码块中x
为发送过去的数据,h
为发送的HTTP请求,o
为返回的数据。
通过对h.onload
的函数部分编辑来进行返回后的事件编写。
相关代码块(JS)
var x={};
x.authenticity_token=$("meta[name='csrf-token']").attr("content");
x.department_id=e.target.getAttribute("data-id");
x.specify=parseInt(id);
var h=new XMLHttpRequest();
h.open('POST','/show_speciality');
h.setRequestHeader('Content-Type','application/json');
h.onload=function()
{
console.log(h.response);
var o=JSON.parse(h.response);
console.log(o.status);
console.log(o.message);
console.log(o.data);
if (o.status=="200"){
for (var i=0;i<o.count;++i)
{
var newli=document.createElement("li");
newli.setAttribute("data-id",o.data[i].id);
if (o.data[i].name)
newli.innerHTML=o.data[i].name;
else
{
newli.innerHTML=o.data[i].course_name;
}
document.getElementById('ul'+(parseInt(id)+1).toString()).appendChild(newli);
}
}
}
h.send(JSON.stringify(x));
console.log(JSON.stringify(x));