简体   繁体   English

如何正确传递JSON数组?

[英]How to pass JSON array correctly?

i am trying to create a fade effect with the following...ive been told im nearly there apart from the passing of the json array. 我正在尝试使用以下内容创建淡入淡出的效果...除了JSON数组的传递之外,我还被告知即时消息。 At the moment no images are displayed. 目前没有图像显示。

 //generate all the boxes
$.get('images.php',function(data){
  for (var i=0; i < totalBoxes; i++){
      var randomImage = data[Math.floor(Math.random() * data.length)];
      $('<div class="pf-box"><img class="black" src="' + randomImage['black'] + '" /><img class="colour" src="' + randomImage['colour'] + '" /></div>').hide().appendTo('#bg').fadeIn('slow').filter('.colour').css("opacity", 0);
  }
 },'json');

 //add the hover behavior to all the elements
 $('.colour').hover(function() {
   $(this).stop().fadeTo(700, 1);
 },function() {
   $(this).stop().fadeTo(700, 0);
 });

and images.php 和images.php

    <?php 
   header('Content-type: application/json');
echo '[  
    {'black' : 'images/random/1.jpg', 'colour' : 'images/random/1-c.jpg'},  
    {'black' : 'images/random/2.jpg', 'colour' : 'images/random/2-c.jpg'}
]';
    ?>

Don't you need to escape the quotes inside the JSON string? 您是否不需要转义JSON字符串中的引号? Otherwise the php interpreter will fail to send all of what you want, and may even barf out some errors. 否则,PHP解释器将无法发送所有您想要的内容,甚至可能阻止某些错误。

使用randomImage.black代替randomImage ['black']

Your echo is failing because of the single quotes in the JSON output breaking out of the echo. 由于JSON输出中的单引号超出了回声,因此您的回声失败了。

Enclose your string with different quotes so you can echo properly: 将字符串用不同的引号引起来,以便可以正确地进行回显:

<?php
header('Content-type: application/json'); 
echo "[
    {'black' : 'images/random/1.jpg', 'colour' : 'images/random/1-c.jpg'},
    {'black' : 'images/random/2.jpg', 'colour' : 'images/random/2-c.jpg'} 
]"; 
?>

Note the use of double quotes to enclose the echo string, instead of the single quotes you've used. 请注意,使用双引号将回声字符串括起来,而不是使用单引号。 (if you had double quotes inside the string, then you'd reverse it and use single on the outside). (如果字符串中有双引号,则可以将其取反,并在外部使用单引号)。

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

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