这是我的:
function loadGraphs(datawijk){
$.ajax({
url: './api5.php', //the script to call to get data
data: {
wijk: datawijk,
}, //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
var htmlContent = "";
// ADD TO
htmlContent += '<tr><th scope="row">Geboortes</th>';
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
htmlContent +=
'<td>' + year + '</td>';
});
});
htmlContent += '</tr>';
var lol = updateOverlijdens(datawijk, htmlContent);
alert(lol);
$('#graphs table tbody').html(htmlContent);
}
});
}
function updateOverlijdens(datawijk, htmlContent){
$.ajax({
url: './api4.php', //the script to call to get data
data: {
wijk: datawijk,
}, //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
// ADD TO
htmlContent += '<tr><th scope="row">Overlijdens</th>';
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
htmlContent +=
'<td>' + year + '</td>';
});
});
htmlContent += '</tr>';
return htmlContent;
}
});
}
当我发出警报时(笑);在函数 loadGraphs 中,我得到 undefined ... 当我做 alert(htmlContent);在函数 updateOverlijdens 中,就在我返回值之前,我做对了。仅当我提醒我的函数 loadGraphs 中的值时,我才得到未定义。我该如何解决这个问题?
最佳答案
你变得未定义的原因是你没有从 updateOverlijdens
返回任何东西(但是从成功的内部函数)
您正在运行异步代码,通常您无法使用当前使用的函数返回模式轻松解决此问题,因为返回时数据不可用。您需要的是回调。
请参阅this page有关 jQuery ajax 的良好用法示例。您想要做的是将一个函数传递给 updateOverlijdens 并在您的 ajax 成功回调触发时调用它。在网上(以及上面的链接中)有很多这样的例子。
例如,这是修改为正确的回调模式后的代码,它解决了异步执行的问题
function loadGraphs(datawijk){
$.ajax({
url: './api5.php', //the script to call to get data
data: {
wijk: datawijk,
}, //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
var htmlContent = "";
// ADD TO
htmlContent += '<tr><th scope="row">Geboortes</th>';
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
htmlContent +=
'<td>' + year + '</td>';
});
});
htmlContent += '</tr>';
updateOverlijdens(datawijk, htmlContent,function(lol){
alert(lol);
$('#graphs table tbody').html(lol);
});
}
});
}
function updateOverlijdens(datawijk, htmlContent,callback){
$.ajax({
url: './api4.php', //the script to call to get data
data: {
wijk: datawijk,
}, //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
// ADD TO
htmlContent += '<tr><th scope="row">Overlijdens</th>';
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
htmlContent +=
'<td>' + year + '</td>';
});
});
htmlContent += '</tr>';
callback(htmlContent)
}
});
}
关于php - Javascript 函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425592/