簡體   English   中英

將php數組發送到jquery ajax並從該數組中創建每個循環

[英]Send php array to jquery ajax and make a each loop from that array

嗨,實際上我讀了很多關於數組和jquery的話題,他們都在hmtl腳本標簽里面顯示了使用jquery的例子,但我試着學習的是如何讀取php發送的數據通過jj文件中的ajax

這是我的php示例

$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);

那么這是我的ajax

$.ajax({
    url: "system/music_list.php",
    dataType: 'json',
    cache: false,
    success: function(response){
        // here i want to read the array and make a loop for each element 
    },
});

謝謝,如果你能幫助我

嘗試使用長度計數的基本循環這個..這應該有幫助。

 function ajax_test()
 {
    $.ajax({
        url: "system/music_list.php",
        dataType: 'json',
        cache: false,
        success: function(response)
        {
             for (var i = 0; i < response.length; i++)
             {
                 alert(response[i]);
             }
        }
    });
 }

請使用以下代碼:

$(response).each(function(key,value){
    console.log(value);
});

這里響應數組和值的每個循環得到('jazz',rock,...等)。

嘗試使用for loop來循環記錄

$.ajax({
    url: "system/music_list.php",
    dataType: 'json',
    cache: false,
    success: function(response){
        var record;
        for(record in response)
        {
            console.log(response[record]); 

        });
    },
});

$ .each :通用迭代器函數,可用於無縫迭代對象和數組。 具有length屬性的數組和類似數組的對象(例如函數的參數對象)由數字索引迭代,從0到length-1。 其他對象通過其命名屬性進行迭代。 參考文檔

$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
 //Check if the response is in expected JSON format.
  var flag = isJSON(response);
    if(flag === true)   
    { response = JSON.parse(response);  }              
    //Iterate the Array using for each loop of jquery
    $.each(response, function( index, value ) {
      console.log( "Index : " + index + "Value : " + value );
    });
  } // End of success function
}); //End of Ajax

//JSON format check
function isJSON(data) {
   var ret = true;
   try {
      JSON.parse(data);
   }catch(e) {
      ret = false;
   }
   return ret;
}

您可以通過在jQuery中使用.each來獲取數組索引和值:

$.ajax({
    url: "system/music_list.php",
    dataType: 'json',
    cache: false,
    success: function(response){
        $.each(response, function(index,value)
        {
            console.log(index); // print all indexes
            console.log(value); // print all values
        });
    },
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
    $.ajax({ url: "music_list.php",
             dataType: 'json',
             cache: false,
             success:function(response) { 
                 for( res in response) {
                     document.getElementById('dat').innerHTML+=response[res]+"<br/>"; 
                 }
             }
         });
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM