【问题标题】:php array to javascript array format [closed]php数组到javascript数组格式[关闭]
【发布时间】:2013-09-09 09:27:52
【问题描述】:

php数组:

Array([0] => http://XXX/xgsyw/content/Uploads/Img/1111.jpg[1] => http://XXX/xgsyw/content/Uploads/Img/222.jpg)

到javascript“图像”

$('#top').bgStretcher({
        images: ['images/sample-1.jpg', 'images/sample-2.jpg', 'images/sample-3.jpg', 'images/sample-4.jpg', 'images/sample-5.jpg', 'images/sample-6.jpg'],
        slideDirection: 'N',
        slideShowSpeed: 1000,
        transitionEffect: 'fade',
        sequenceMode: 'normal',
    });

【问题讨论】:

  • 您的问题可能是? (不,除非您付出努力,否则我们不会为您编写代码。)
  • 猜谜题能得到赏金吗?
  • 提示:json_encode().
  • 下次认真首先使用 GOOGLE 或 STACKOVERFLOW 搜索!!! 如果您准确输入了标题,那么您的答案就会作为第一个搜索结果。 bit.ly/1dUJ6vl

标签: php javascript arrays


【解决方案1】:

使用JSON 库对其进行编码。将其发送回 Javascript,对其进行解码,然后将新的 img 子节点附加到某个容器。

echo json_encode(arrayOfImages);

然后在你的 JS 中:

var images = JSON.decode(returnValue);

images.each(function(path) {
   var img = $('<img>');
   img.attr('src', returnValue);
   img.appendTo('#imagediv');
});

如 cmets 中所述..

使用$(document.createElement("img")); 比使用上述建议更快。

【讨论】:

  • 这会更快var img = $( document.createElement("img") );,原生变体比jQuery更快
  • 编辑成问题。谢谢。
  • 哦,谢谢,但我不知道该怎么做
【解决方案2】:

您可能已经在网上进行了更多研究,因为您的解决方案需要的是 JavaScript Object Notation 短 JSON。

使用json_encode($your_array);

http://php.net/manual/de/function.json-encode.php

【讨论】:

  • "[\"的结果http:\\/\\/localhost\\/xgsyw\\/content\\/Uploads\\/Img\\/1111.jpg\",\ "http:\\/\\/localhost\\/xgsyw\\/content\\/Uploads\\/Img\\/222.jpg\"]"
  • 不能在javascript中使用
  • 参数2有转义功能,建议你找php.net的文档:)
  • 是的,我看到了,但会出错“json_encode() 只需要 1 个参数,给定 2 个”我的代码“echo json_encode($array,JSON_HEX_TAG);”
  • 您也可以在 php.net 上找到,这些选项仅适用于 php 5.3 或更高版本。请检查您的 php 版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多