我是前端和Web开发的新手,并且遇到了障碍。我最初将网站开发为单页应用程序,经过一些反馈,我决定将其转换为多页应用程序。一切都可以在一个页面上正常运行,但是当我加载与另一个页面相同的HTML时,我的ajax调用中的数据以及我使用javascript生成的HTML都不会显示。
相关代码(请告知我是否需要提供更多信息)。
点击通过此方法生成的exp-button
:
let generateCards = function (data) {
experiments = data;
data.forEach(element => {
let end = new Date(element.endDate);
daysLeft = dateDiffInDays(today(), end);
if (daysLeft <= 0) {
daysLeft = "Experiment Ended";
}
if (daysLeft === 1) {
daysLeft = "Ends Today";
}
let cardHtml = '<div class="card-container .col-md-4 .offset-md-4">' +
'<div class="cardImg">' +
'</div>' +
'<div class="experiment">' +
'EXPERIMENT' +
'</div>' +
'<div class="experiment-name">' +
element.title +
'</div>' +
'<div class="experiment-description">' +
element.shortDescription +
'</div>' +
'<div class="experiment-time-remaining">' +
daysLeft + ' days left' +
'</div>' +
`<a class="exp-button" data-experiment="${element.id}">` +
'<div class="experiment-button">' +
'<div class="button-text">' +
'LEARN MORE' +
'</div>' +
'</div>' +
'</a>' +
'</div>';
$('#cards-container').append(cardHtml);
});
};
请注意,我还尝试了以下代码行,而不是下面的方法:
`<a class="exp-button" href="experiment.html" onclick=loadLearnMore(${element.id}) data-experiment="${element.id}">`
click方法(在$(document).ready(function ()
内部):
$(document).on('click', '.exp-button', function (event) {
//event.preventDefault();
id = $(this).attr("data-experiment");
loadLearnMore(id);
window.location.href= "/experiment.html";
});
这应该触发此方法,我在尝试的某些配置中遇到断点,但从未显示数据:
let loadLearnMore = function (id) {
$.ajax({
method: "POST",
url: "http://localhost:55345/api/ExperimentParticipant",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(id),
success: function (res) {
},
error: function (data, err) {
console.log(err);
}
}).done(function (result) {
$("#participants").html('');
$("#participants").append(result);
experiment = experiments.filter(e => e.id == id);
$("#days-remain").html('');
$("#days-remain").append(dateDiffInDays(today(), new Date(experiment[0].endDate)));
$(".experiment-text-learn").html('');
$(".experiment-text-learn").append(experiment[0].title);
$(".about-text").html('');
$(".about-text").append(experiment[0].longDescription);
$(".duration-text").html('');
$(".duration-text").append(longDate(new Date(experiment[0].startDate)) + ' - ' + longDate(new Date(experiment[0].endDate)));
$('#join-button').attr("data-experiment", id);
loadRequirements(id);
loadUpdates(id);
loadNextStaps(id);
});
};
先前方法中使用的其他方法:
let loadNextStaps = function (id) {
$.ajax({
method: "GET",
url: "http://localhost:55345/api/join/" + id,
dataType: "json",
contentType: "application/json",
success: function (res) { },
error: function (data, err) {
console.log(err);
}
}).done(function (result) {
let steps = (JSON.parse(result));
let content = '';
steps.forEach(element => {
var media;
content += `<div>${element.number}. ${element.step}</div>`;
if (element.isApp === true) {
media = element.mediaUrl.split(' ');
if(media[0] != 'null'){
content += `<a href='${element.appleUrl}' target='_blank'><img src='${media[0]}' alt='app store logo'></img></a>`;
}
if(media[1] != 'null'){
content += `<a href='${element.androidUrl}' target='_blank'><img src='${media[1]}' alt='google play logo'></img></a>`;
}
}
});
$("#next").html('');
$("#next").append(content);
});
};
let loadUpdates = function (id) {
$.ajax({
method: "GET",
url: "http://localhost:55345/api/updates/" + id,
dataType: "json",
contentType: "application/json",
success: function (res) { },
error: function (data, err) {
console.log(err);
}
}).done(function (result) {
let updates = (JSON.parse(result));
let content = '';
updates.forEach(element => {
content += `<div class='update-time'>${timeSince(element.date)}</div>` + //time since
`<div class='update-title'>${element.title}</div>` + //title
"<div class='update-text-container col-md-8'>" +
"<div class='update-text'>" +
`${element.content}` + //update content
"</div>" +
"</div>";
});
$("#profile").html('');
$("#profile").append(content);
});
};
let loadRequirements = function (id) {
$.ajax({
method: "GET",
url: "http://localhost:55345/api/requirements/" + id,
dataType: "json",
contentType: "application/json",
success: function (res) { },
error: function (data, err) {
console.log(err);
}
}).done(function (result) {
let requirements = (JSON.parse(result));
$('.requiirement-list').html('');
requirements.forEach(element => {
$('.requiirement-list').append(`<li class="requiirement-item">${element.content}</li>`);
});
});
};
答案 0 :(得分:2)
window.location.href= "/experiment.html";
删除此行
您要先浏览器离开,然后才能执行其余脚本。
答案 1 :(得分:1)
我在您的代码中看到的问题是:
当单击.exp-button
时,loadLearnMore
函数将在当前页面执行(例如,其index.html
),然后在执行该功能后立即导航到新页面(实验)。 html),这样就不会对您刚刚在页面上执行的javascript代码进行任何更改,因为您现在位于新页面上。
我建议单击.exp-button
时,首先要导航到新页面(例如experiment.html
并将id作为参数传递到新页面),然后在该页面上执行javascript / ajax请求。
以下是一些基本代码来说明其工作方式(我知道您正在动态生成html,这也可以正常工作,但我只是对其进行了硬编码以进行演示):
<!DOCTYPE html>
<html>
<head>
<title>Index page</title>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.exp-button', function (event) {
//event.preventDefault();
id = $(this).attr("data-experiment");
//navigate to experiment.html passing the id as a parameter.
window.location.href= "experiment.html?id=" + id;
});
});
</script>
</head>
<body>
<div id="cards-container">
<a class="exp-button" data-experiment="1">learn more</a>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Experiment page</title>
<script src="jquery.min.js"></script>
<script>
//get the url parameters sent
var urlParams = new URLSearchParams(window.location.search);
//get the id parameter and store it in a global variable
var id = urlParams.get('id');
console.log(id);
$(document).ready(function(){
//do ajax request with the id parameter. This could also be in a loadLearnMore function but Im keeping it basic for demonstration purposes.
$.ajax({
method: "POST",
url: "http://localhost:55345/api/ExperimentParticipant",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(id),
success: function (res) {
},
error: function (data, err) {
console.log(err);
}
}).done(function (result) {
//now that we have the data/result we can insert it to the elements of the current page that we are on as follows.
$("#participants").html('');
$("#participants").append(result);
});
});
</script>
</head>
<body>
<div id="participants"></div>
</body>
</html>