PHP 生成的选项列表仅出现在第一个 Ajax 动态生成的容器上



我遇到了一个问题,我的php生成的选择/选项列表不适用于我所有动态生成的块/容器。它只将 PHP 选择添加到最后一个容器/块实例,尽管为每个容器调用了它。当使用警报进行故障排除时,它似乎在添加容器/块并生成选择之前运行了所有迭代,因此为什么它总是出现在最后一个

n = -1
function addDiv() {
n++;

因此,简要概述 - 在页面上初始化代码将获取数据库中在特定条件下的条目数量,并将该数字应用于"length",然后多次运行函数 addDiv((。通常,当通过按钮一次添加一个块时,它会在 addDiv(( 函数中通过 php 使用选项的选择/列表填充创建的块,但是当使用循环( initialize(( 函数(自动执行此操作时,会出现上述问题。

$( document ).ready(function() {
initialize();
});
function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);
console.log(arrayJson);
length = arrayJson.length;
console.log(length);
for(var i = 0; i < length; i++) {
addDiv();
};
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};

这是与 addDiv 相关的代码,其中包含一些密文,以使其更易于阅读。

var n = -1;
function addDiv() {
n++;
$.post(  
"json-option-generator.php",  
{}                               
).done(                          
function(data)
{
$('#selectedcoin' + n).html(data); 
});
$("<div class='coinmarketcap fill' id='container" 
+ n + 
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin" 
+ n + 
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container"); 
}

最后这里是 PHP 文件的内容,用于基于 JSON 数据生成选项列表 -

<?php
$json = file_get_contents("../ticker/full.json");
$decode = json_decode($json, true);
sort($decode);
echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>

我知道这很混乱,可能需要深入阅读,所以我感谢任何花时间看的人。

有什么明显的东西可以帮助我朝着正确的方向前进吗?我尝试通过使用setTimeout函数包装"addDiv(("来破坏initialize((中的"addDiv(("调用,但没有乐趣。

它应该与此一起使用(为了理解,我以不同的方式命名参数,但indexindex_t都可以命名为n(:

var n = -1;
function sendToGenerator(index){
var index_t = index;
$.post(  
"json-option-generator.php",  
{}                               
).done(                          
function(data)
{
$('#selectedcoin' + index_t).html(data); 
}
);
}
function addDiv() {
n++;
sendToGenerator(n);
$("<div class='coinmarketcap fill' id='container" 
+ n + 
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin" 
+ n + 
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container"); 
}

最新更新