gpt4 book ai didi

javascript - jQuery 和 JSON : loop json array

转载 作者:行者123 更新时间:2023-11-30 17:20:58 24 4
gpt4 key购买 nike

我在数据库中有一个数组:

a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}

所以我用 php 反序列化,然后用 json 编码,代码如下:

$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');

print_r ($unwp);

echo json_encode($unwp);

我在页面上看到了这个:

Array ( [1] => 1993 [2] => 1994 [3] => 1995 [4] => 1996 ) {"1":"1993","2":"1994","3":"1995","4":"1996"}

我需要用 jQuery 以某种方式循环它吗?这样我就可以得到 1993、1994、1995、1996 等等。

我正在测试 jQuery.getJSON(),但不知道如何使用它?

页面上的所有代码:

<?php
$array = $_POST['inputarray'];
$str = serialize($array);
print $str . "\n";
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
?>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script>

jQuery(function ($) {

// Add children input fields
var childBlock = $('.block');
var countChildren = $('div.block div.row').size() + 1;
$('#addChild').live('click', function (e) {
e.preventDefault;
$('<div class="row"><input type="text" name="inputarray['+countChildren+']" id="inputarray'+countChildren+'" placeholder="inputarray['+countChildren+']"><a href="javascript://" id="deleteChild">Delete</a></div>').appendTo(childBlock);
countChildren++;
});
$('#deleteChild').live('click', function (e) {
e.preventDefault();
if (countChildren > 2) {
$(this).parents('div.row').remove();
countChildren--;
var counter = 1;
$('input[name^="inputarray"]').each(function () {
$(this).attr('name', 'inputarray[' + counter + ']');
$(this).attr('placeholder', 'inputarray[' + counter + ']');
$(this).attr('id', 'inputarray' + counter);
counter++;
});

}
});
})(jQuery);

</script>



<form action="" method="post">
<div class="block">
<div class="row"><input type="text" name="inputarray[1]" placeholder="inputarray[1]"></div>
<input type="hidden" value="<?php echo $str; ?>">
</div>
<input type="submit">
</form>


<a href="javascript://" id="addChild">Add a child</a>

谢谢!

最佳答案

这可以在 PHP 中轻松完成。因为我没有看到 submit() 的任何处理程序或 click()或任何可能暗示 ajax 请求的东西。

而且您还在同一个文件中包含了 php,那么为什么不简单地使用 PHP 循环并生成您需要的内容呢?

echo "<select name='year'>";
foreach($unwp as $year) {
echo "<option value='{$year}'>{$year}</option>";
}
echo "</select>";

上面的代码片段将完全满足您的需求。

Example


编辑

您正在尝试生成 <select>正确的?如果没有,请告诉我,以便我可以根据需要进行修改。

关于javascript - jQuery 和 JSON : loop json array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25133320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com