如何通过使用PHP和放大器的阵列;阿贾克斯的Javascript? [英] How to pass an array using PHP & Ajax to Javascript?

查看:102
本文介绍了如何通过使用PHP和放大器的阵列;阿贾克斯的Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果这种解释是不明确的,这对我来说很难理解了。 如何使用PHP和放大器;阿贾克斯发送阵列的Javascript 我使用Ajax获得的照片阵列,这我再想找追加到一个空的< D​​IV> 在我的网页。

Apologies if this explanation isn't clear, it's hard for me to understand too. How can I use PHP & Ajax to send an array to Javascript? I'm using Ajax to get an array of photos, which I'm then looking to append to an empty <div> on my page.

jQuery的如下所示:

The jQuery looks as follows:

$.ajax({
    url: "<?php echo site_url('demo/getPhotos/'); ?>",
    type: 'POST',
    data: form_data,
    success: function(data) {
        alert(data);
   }

和PHP函数getPhotos看起来是这样的:

And the PHP function getPhotos looks like this:

<?php

$photos = array();

foreach ($data as $photo) {
    array_push($photos,$photo['source']);
    }

// echo json_encode($photos); How should I be returning $photos?

如果我只是回声$的照片。将数据发送到成功的回调,但不会出现在可用的格式

If I simply echo $photos; the data is sent to the success callback, but it doesn't appear to be in a usable format.

如果我做了的var_dump($照片)在PHP中,结果看起来是这样的:

If I do a var_dump($photos) in PHP, the result looks something like:

array(4) {
  [0]=>
  string(14) "some_image.jpg"
  [1]=>
  string(14) "some_image.jpg"
  [2]=>
  string(14) "some_image.jpg"
  [3]=>
  string(14) "some_image.jpg"
}

我已经试过 json_en code 之类的各种组合,但确实我猜测,并不能确定其背后的理论。什么是从PHP数据传递为Javascript在这种情况下最好的方法是什么?

I've tried various combinations of json_encode and the like but really I am guessing and not sure of the theory behind it. What's the best way to pass data from PHP to Javascript in this context?

推荐答案

尝试:

$.ajax({
    url: "<?php echo site_url('demo/getPhotos/'); ?>",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        alert(data[0]);
   }

在PHP端,你会想要打印:

On the PHP side, you'll be wanting to print:

print json_encode($photos);

您可以尝试以另一件事,以便更好地封装你code,并作为进一步JSON gooodness一个例子,将是:

Another thing you might try in order to better encapsulate your code, and as an example of further JSON gooodness, would be:

print json_encode(array("photolist"=>$photos,"photo_owner"=>"Me!"));

然后在服务器上,你会与访问这些:

Then on the server, you'd access these with:

data.photolist[0]; //First photo
data.photo_owner;  //The owner of the photo set

这篇关于如何通过使用PHP和放大器的阵列;阿贾克斯的Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆