【问题标题】:How to get the value of n-th item in a JSON list (using JQuery)?如何获取 JSON 列表中第 n 项的值(使用 JQuery)?
【发布时间】:2010-07-26 02:19:33
【问题描述】:

如何检索 JSON 文件中的第 n 个值(也可能是子文件)?

例如,我有一个 JSON 格式的课程和相关事件的集合,我用它来填充几个选择列表,例如:

// extract from courselist.php
[{
    "optionValue": "Getting Research into Practice",
    "events": [
        {"date": "29 October"}
    ] 
},
{
    "optionValue": "Human Resources for Managers",
    "events": [
        {"date": "September 1"},
        {"date": "November 2"}
    ]
}]

我这样做是为了从该 JSON 创建表单:

$(function(){
$("select#coursetype").change(function(){
    $.getJSON("courselist.php",{id: $(this).val(), ajax: 'true'}, function(data){
        var options = ''; //item in select list
        options += '<option value=""></option>';
        for (var i = 0; i < data.length; i++) {
            options += '<option value="' + [i] + '">' + data[i].optionValue + '</option>';  
            $("#courselist").html(options);
            $('#courselist option:first').attr('selected', 'selected');
        };
    })
})  
});

.. 输出 HTML 如下:

<select id="coursetype" name="coursetype">
    <option value="0">Getting Research into Practice</option>
    <option value="1">Human Resources for Managers</option>
</select>

假设,用户选择“经理的人力资源”(值 =“1”),并 $_POST 表单,我以后如何从 POST 值中检索该课程名称及其事件信息?

【问题讨论】:

    标签: jquery json forms


    【解决方案1】:

    如果您仍然有可用的 JSON 对象,您可以将 feed the posted value back 作为索引放入其中:

    var courseName = data[postValue].optionValue;
    var courseEvents = data[postValue].events;
    for(theDate in courseEvents){
        // do something with the date
    }
    

    【讨论】:

    • 这就是我所需要的。非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多