我有以下网址:
http://domain.com/details.aspx?number=2012-001
我想匹配 URL 字符串中的“number”参数并仅显示与其关联的 JSON 数据,因此在本例中我只想渲染 JSON 数组中的第一个对象。
这是 JSON 结构:
{
"notices": [
{
"number": "2012-001",
"link": "www.google.com",
"title": "sample title",
"awardClaimDueDate": "3/1/2015",
"awardClaimForms": "abc.pdf",
"datePosted": "1/31/2012"
},
{
"number": "2012-002",
"link": "www.yahoo.com",
"title": "sample title",
"awardClaimDueDate": "4/3/2015",
"awardClaimForms": "file.doc",
"datePosted": "2/3/2012"
}
]
}
我尝试编写 JS,但很难仅显示与数字关联的值。仍然是菜鸟,因此我们将不胜感激您的帮助!
function jsonParser(json){
$('#load').fadeOut();
$.getJSON('notices.json',function(data){
// Parse ID param from url
var noticeParamID = getParameterByName('number');
$.each(data.notices, function(k,v){
var noticeNumber = v.number,
noticeTitle = v.title,
claimDueDate = v.awardClaimDueDate,
claimForms = v.awardClaimForms,
date = v.datePosted;
if(noticeParamID == noticeNumber){
// how can I display content that matches the url param value (noticeURLNumber)?
}
});
});
}
// get URL parameter by name
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
最佳答案
您需要将 HTML 渲染到 #load div,如下所示:
function jsonParser(json) {
$.getJSON('notices.json',function(data){
// Parse ID param from url
var noticeParamID = getParameterByName('number');
$.each(data.notices, function(k,v){
var noticeNumber = v.number,
noticeTitle = v.title,
claimDueDate = v.awardClaimDueDate,
claimForms = v.awardClaimForms,
date = v.datePosted;
if (noticeParamID == noticeNumber) {
// display content
var noticeHtml = '<h1>' + noticeNumber + '</h1>' +
'<h2>' + noticeTitle + '</h2>...';
$('#load').html(noticeHtml).show();
}
});
});
}
// get URL parameter by name
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Run it
jsonParser();
PS - $('#load').fadeOut() 导致内容显示出现问题,因此我将其从本示例中删除。
这是一个显示其工作原理的 fiddle :https://jsfiddle.net/uyw3j2c7/
关于javascript - 使用 JQuery 和 AJax 显示 JSON 中的选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576690/