将 php 数组发送到 jquery ajax 并从该数组创建一个 each 循环
Send php array to jquery ajax and make a each loop from that array
嗨,实际上我读了很多关于数组和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>
相关文章:
- 从多维嵌套json数组创建下拉列表
- 为对象数组创建列表项
- 如何在cycle js中从JSON数组创建组件
- 使用数据数组创建多个类似组件
- 如何在 Angular JS 中从关联数组创建多个复选框
- 如何为给定数组创建跨度列表
- 如何在javascript中使用2个一维数组创建层次结构树
- 从数据对象数组创建折线图
- 从 javascript 数组创建一个 Jquery 数组
- Angular2从数组创建一个列表
- 使用JavaScript's Reduce从对象数组创建数组
- 如何从数组创建 jqtree
- 从字符串数组创建唯一组合数组
- 反应.js通过数组创建循环
- 从数组创建新元素,直到每秒数组为空
- 如何使用其他流的值数组创建流
- JavaScript:从字节数组创建图像资源
- 使用拆分字符串的数组创建一个对象
- 从一组数据或数组创建对象
- 多维数组 - 创建一个表