Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

How to pass an array using PHP & Ajax to Javascript?

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.

The jQuery looks as follows:

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

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.

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"
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

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

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

print json_encode($photos);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...