[英]Want to get value from an array in javascript
Here, I am getting value in javaScript ajax as an array. 在这里,我在javaScript ajax中获得了一个数组的价值。 I want only value from an array. 我只想要数组中的值。 My array is like, 我的数组就像
data:
monthArray
(
[0] => Array
(
[Name] => abc
[total_point] => 100
[total_earn_point] => 0
)
)
weekArray
(
[0] => Array
(
[Name] => xyz
[total_point] => 100
[total_earn_point] => 0
)
)
Here, 这里,
function emp_perf(){
jQuery.ajax({
url: "<?php echo base_url(); ?>grade_tasks/emp_performance",
data:'',
type:"GET",
success:function(data){
alert(data[0]);
},
error:function (){}
});
}
setInterval(emp_perf, 3000);
Here, I could not fetch. 在这里,我无法获取。 I want data as, separate in javascript variable. 我想要数据,在javascript变量中分开。
So, how can this be done in javascript? 那么,如何在javascript中完成呢? (Updated) (更新)
success:function(data){
// Both the below method works.
alert(data["monthArray"][0].name); // will alert abc
alert(data["monthArray"][0]["total_point"]); // will alert 100
// Loop through data[0]
for(var i in data["monthArray"][0]){
alert(data["monthArray"][0][i]);
}
},
Explaination: 说明:
Your data is an object, so you can access its elements using the key. 您的数据是一个对象,因此您可以使用键访问其元素。 data.monthName
or data["monthName"]
, now data.monthName
is an array and you can access it's values using []
whose first element is an object again use same notation to fetch its values. data.monthName
或data["monthName"]
,现在data.monthName
是一个数组,您可以使用[]
访问其值, []
的第一个元素是一个对象,再次使用相同的符号来获取其值。
Return the data as JSON, is the best way to interact between PHP & Javascript. 以JSON形式返回数据,是在PHP和Javascript之间进行交互的最佳方式。 Then you can use JSON.parse
to convert the JSON to a javascript object/array. 然后,您可以使用JSON.parse
将JSON转换为javascript对象/数组。
PHP 的PHP
<?php
//emp_performance
die(json_encode($dataArray));
?>
Javascript Java脚本
function emp_perf(){
jQuery.ajax({
url: "<?php echo base_url(); ?>grade_tasks/emp_performance",
data:'',
type:"GET",
success:function(data){
data = JSON.parse(data);
//you can use $.parseJSON(data) too since you are using jQuery
console.log(data.MonthArray);
console.log(data.MonthArray[0].Name);
console.log(data.MonthArray[0].total_point);
console.log(data.MonthArray[0].total_earn_point);
console.log(data.WeekArray);
console.log(data.WeekArray[0].Name);
console.log(data.WeekArray[0].total_point);
console.log(data.WeekArray[0].total_earn_point);
},
error:function (){}
});
}
setInterval(emp_perf, 3000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.