简体   繁体   English

Jquery获取所有数组元素

[英]Jquery Get all the array elements

I am programming beginner.. 我是编程初学者..

Code

 <script type="text/javascript">
     $(function() {
       var course_category = "<?php echo $_REQUEST['cities'] ?>";
       alert(course_category); // alerts as Array
   });

when i do print_r in php ( print_r($cities); ) i get 当我在php( print_r($cities); )中执行print_r时,我得到了

  Array ( [0] => BLR [1] => DEL [2] => HYD [3] => MUM

now i want to print the array in above jquery 现在我想在上面的jquery中打印数组

try 尝试

 $.each(course_category, function(key,value){
   alert(value); 

}};

printns A,r,r,a,y printns A,r,r,a,y

正确的方法是使用JSON:

var list = <?php echo json_encode($_REQUEST['cities']); ?>;

I assume you currently have two problems: 我假设你目前有两个问题:

  1. Your PHP array is not encoded in any way, that JavaScript understand. 您的PHP数组以任何方式编码,JavaScript理解。 Just use json_encode() here. 在这里使用json_encode()

  2. If you receive an object (and arrays are just objects for that matter), you can't just output them using alert() , if you really want to see the contents. 如果你收到一个对象(并且数组只是那个问题的对象),你不能只使用alert()输出它们,如果你真的想看到内容的话。 Again, you may use JSON.stringify() to solve this. 同样,您可以使用JSON.stringify()来解决此问题。

$(function() {
 var course_category = "<?php echo json_encode( $_REQUEST['cities'] ); ?>";
 alert( JSON.stringify( course_category) );
});

If you want to use the array contents later on, refer to plain for loops or jQuery's each() . 如果您想稍后使用数组内容,请参阅plain for循环或jQuery的each()

<?php
$output = '';
foreach($_REQUEST['cities'] as $city){
    $output .= "'$city',";
}
$output = rtrim(",", $output);
?>
var course_category = [<?php echo $output; ?>];

You can use .each in jQuery to iterate an array 您可以在jQuery中使用.each来迭代数组

  $.each(course_category , function(index, item) {
});

Actually i dont know about php.But you can iterate an array using the above code in jQuery 其实我不知道php.But你可以使用jQuery中的上述代码迭代一个数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM