嗨,实际上我读了很多关于数组和jQuery的主题,它们都显示了在HMTL脚本标签中使用jQuery的示例,但我试图学习的是如何在JS文件中读取PHP通过AJAX发送的数组
这是我的 PHP 示例
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
那么这是我的阿贾克斯
$.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
},
});
谢谢,如果你能帮助我
尝试使用长度进行计数的基本 for 循环 这应该肯定会有所帮助。
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]);
}
}
});
}
尝试使用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]);
});
},
});
请使用以下代码:
$(response).each(function(key,value){
console.log(value);
});
在这里,响应数组和值的每个循环都得到('爵士',摇滚,...等(。
请尝试查看此内容,为您的问题提供清晰的解决方案
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.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>