如何从 AJAX jquery 函数访问多维关联 json 数组



我必须从 PHP 页面返回一个 jQuery AJAX 函数的多维关联数组。

这是我的PHP页面,叫做'seachsongs.php

     <?php
$brano = $_POST['brano'];
    $sql = "SELECT Titolo, Autore FROM Brani WHERE Titolo = '$brano';";
    $ris = $conn->query($sql);

    while ($row = $ris->fetch_array()) {
        $arr[] = $row;
    }
    echo json_encode(array('data' => $arr));
    ?>

这是我的jQuery AJAX函数

$(document).ready(function () {

    $('#nBrano').keyup(function () {
        nomeBrano = $(this).val();
        $.ajax({
            type: "POST",
            data: {brano: nomeBrano},
            url: "searchsong.php",
            success: function (data) {
                document.write(data);
                //alert("Prova" + data['data'][0]["Titolo"]);
                /*if (msg != 'null') {
                    $('#similarSongs').css('display', 'block');
                    /*$.each(prova, function (key1, value1) {
                        $.each(value1['two']['three'], function (key1, value1) {
                            document.write('test');
                        });
                    })
                    $('#similarSongs table').html(tabella);
                }
                if (msg == 'null') {
                    $('#similarSongs table').html("Nessun brano simile trovato");
                    $('#similarSongs').css('display', 'block');
                }*/
            },
            error: function () {
                //alert('errore');
            }
        });
    });
});

如何从 jQuery 访问数组数据?正确的说法是什么?

alert(data)

打印此

{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}

PS:对不起,我的英语不好。

我已将此请求的数据类型设置为 json ,因此返回的响应应该是json对象。您可以通过以下方式访问它:

$(document).ready(function () {
    $('#nBrano').keyup(function () {
        nomeBrano = $(this).val();
        $.ajax({
            type: "POST",
            data: {brano: nomeBrano},
            url: "searchsong.php",
            dataType:'json',
            success: function (response) {
                for(var i=0; i<response['data'].length; i++){
                    console.log(response['data'][i][/*your_target_index*/]);
                }
            },
            error: function () {
                //alert('errore');
            }
        });
    });
});

查看更多关于阿贾克斯的信息

最新更新