php数组通过AJAX进入下拉框

时间:2015-12-28 23:03:03

标签: javascript php arrays ajax

我有几个下拉框。我希望第一个选择类别,然后对PHP文件进行AJAX调用,选择相应的子类别数组并将其返回到第二个下拉列表。代码如下:

包含子类别的PHP文件:

    $category = $_POST['category'];

if ($category == "World"){
$subcategory = array('Europe' => "Europe", 'North America' => "North America", 'South America' => "South America");}
    else if ($category == "Sport"){
$subcategory = array("Football , Football", "Rugby , Rugby", "Cricket , Cricket"); }
echo json_encode($subcategory);

AJAX

function getsub(category, subcategory) {

var category = document.getElementById('category').value;
$('#subcategory').empty();
$('#subcategory').append("<option>loading...</option>");

//kicking off AJAX
$.ajax({
    url: "../php/subcategory.php",
    type: "POST",
    async: true,
    //this is where we define the data that we will send
    data: {
        category: category,
    },
    success: function (subresults) {
        var subresults = JSON.parse(subresults);
        $('#subcategory').empty();
        $('#subcategory').append("<option value='0'>----Select Sub Categry---</option>");
        $.each(subresults, function (i, item) {

            $('#subcategory').append('<option value="' + subresults[i].id + '">' + subresults[i].name + '</option>');

        });
    },
});
return false;
}

我这样做的原因是因为我希望将子类保留在服务器端并且易于更新而不干涉代码。目前,这是将数组中的项目输出到下拉框中,但它们是未定义的。你能帮我把正确的值输出到下拉框吗?

2 个答案:

答案 0 :(得分:1)

有一件事是,如果您将选项的值和标签设置为相同,则无需使用不必要的密钥将数组设置为'Europe' => "Europe"。只需像这样设置数组

$subcategory = array("Europe", "North America", "South America");

在你的JS中,设置值和标签如下:

$.each(subresults, function (i, item) {
     $('#subcategory').append('<option value="' + item + '">' + item + '</option>');
});

但是,如果你想保留单独的价值和标签:

$subcategory = array('EU' => "Europe", 'NA' => "North America", 'SA' => "South America");

然后设置选项值和标签,如下所示:

$.each(subresults, function (i, item) {
     $('#subcategory').append('<option value="' + i + '">' + item + '</option>');
});
  

使用subresults[i]是不必要的,因为您的值已经为item,相当于subresults[i]

答案 1 :(得分:0)

在您的AJAX中,您需要subresults[i].idsubresults[i].name,因此在定义PHP数组时必须使用此结构:

if ($category == "World"){
    $subcategory = array(
        array('id' => "Europe", 'name' => "Europe"),
        array('id' => "North America", 'name' => "North America"),
        array('id' => "South America", 'name' => "South America")
    );}
else if ($category == "Sport"){
    $subcategory = array(
        array('id' => "Football", 'name' => "Football"),
        array('id' => "Rugby", 'name' => "Rugby"),
        array('id' => "Cricket", 'name' => "Cricket")
    ); }
echo json_encode($subcategory);