I've a sample JSON as given below:
[
{
"componentid": 4,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "theme",
"shortdesc": "to set theme for different applications"
},
{
"componentid": 7,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "preferences",
"shortdesc": "preferences screen for apps"
}
]
And I prepared a HTML content based on that data. Code is given below:
function prepareTopComponentList(data) {
var preparedHtml = "";
for (var count = 0; count < data.length; count++) {
preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
" <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
" <img class=\"img-fluid\" src=\"";
preparedHtml += data[0].displayImageUrl;
preparedHtml += "\" alt=\"N/A\">\n" +
" <div class=\"card-body\">\n" +
" <h4 class=\"card-title\">";
preparedHtml += data[0].title;
preparedHtml += "</h4>\n" +
" <p class=\"card-text\">";
preparedHtml += data[0].shortdesc;
preparedHtml += "</p>\n" +
" <a onclick = \"redirect(this, this);\" href='#' class=\"btn btn-info\" id=\"";
preparedHtml += "component_desc_" + data[count].componentid;
/*I replaced 0 with count so that we can get proper ids*/
//console.log(data[0].componentid);
preparedHtml += "\">Learn more</a>\n" +
" </div>\n" +
"\n" +
" </div>\n" +
" </div>";
}
$("#div_top_component").append(preparedHtml);
}
Now, I'm redirecting to a page based on value of componentid
. Redirection function code is given below:
function redirect(element, data) {
// data = prepareTopComponentList(data);
for (var count = 0; count < data.length; count++) {
var url = "inside.dell.com";
var query = data[count].componentid;
var finalUrl = "inside.dell.com/componentid=" + query;
console.log(finalUrl);
}
window.location = "inside.dell.com/componentid=" + query;
}
When I run this code, I get this error:
The requested URL /Reusable Components/pages/inside.dell.com/componentid=undefined was not found on this server.
That error is fine, I don't have any problem with that. However in redirection URL, component id is undefined
. How do I make sure that value of component ID gets passed to URL?
用于windows.location
的变量query
在for
循环块中定义,因此在其外部未定义。
In your HTML
"<a onclick = \"redirect(" + data[count].componentid + ");\" href='#' class=\"btn btn-info\" id=\"";
And then your function
function redirect(id) {
window.location = "inside.dell.com/componentid=" + id;
}
Declare your query
variable outside of for loop.
function redirect(element, data) {
// data = prepareTopComponentList(data);
var query;
for (var count = 0; count < data.length; count++) {
var url = "inside.dell.com";
query = data[count].componentid;
var finalUrl = "inside.dell.com/componentid=" + query;
console.log(finalUrl);
}
window.location = "inside.dell.com/componentid=" + query;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.