2017-02-10 168 views
-2

我必须从PHP页面为jQuery AJAX函数返回一个多维关联数组。如何从AJAX访问多维关联json数组jquery函数

这就是所谓的我的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:抱歉,形成我的英语不好。

+0

你会希望你以后它'data'办? – imudin07

+0

这是从一个pdo中的fetchAll? – 25r43q

+0

您可以将'dataType:'json''添加到您的Ajax调用中,然后jQuery会将它转换为您。 –

回答

0

我已将此请求的数据类型设置为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'); 
      } 
     }); 
    }); 
}); 

see more about ajax

+0

你应该包括你已经改变了什么以及为什么他应该使用它。不只是发布代码块...顺便说一句,'document.write(data)'不会再那么漂亮了,因为'data'现在是一个json对象。 –