如何使用PHP和Ajax将数组传递给Javascript?

时间:2022-12-06 21:37:07

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.

如果这个解释不清楚,我也很难理解。如何使用PHP和Ajax向Javascript发送数组?我使用Ajax获取一个照片数组,然后在页面上添加一个空的

The jQuery looks as follows:

jQuery的外观如下:

$.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函数getPhotos是这样的:

<?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.

如果我只是回显$photos;数据被发送到success回调,但它似乎不是可用的格式。

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

如果我在PHP中做一个var_dump($photos),结果是:

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?

我尝试过各种json_encode之类的组合,但我只是猜测,不确定背后的理论。在此上下文中,将数据从PHP传递到Javascript的最佳方式是什么?

5 个解决方案

#1


20  

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:

在PHP方面,您需要打印:

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

#2


8  

I made an array $result in PHP and at the end of request.

我在PHP和请求结束时创建了一个$result数组。

 echo json_encode($result); 

and in JS $.post handler function :

在JS美元。邮政处理函数:

var obj = $.parseJSON(data);
var v = data.k; 

where k is key value in associative array.

其中k是关联数组中的键值。

#3


2  

json_encode is definitely the way to go. jQuery even has built-in support for parsing JSON. You could use e.g.

json_encode一定是可行的。jQuery甚至还内置了解析JSON的支持。你可以使用。

$.ajax({
    url: "<?php echo site_url('demo/getPhotos/'); ?>",
    type: 'POST',
    data: form_data,
    dataType: 'json', // will automatically convert array to JavaScript
    success: function(array) {
        alert(array[0]); // alerts first string
    }
});

#4


0  

return the json itself and then construct the array in js by looping over the json as follows:

返回json本身,然后在json上循环构建js中的数组,如下所示:

var array=[];
for(var key in json)
{    
    if(json.hasOwnProperty(key))
      array.push(json[key]);
}

Or you can simply work with the json itself any reason for needing the array?

或者,您可以简单地使用json本身,有什么理由需要这个数组吗?

something like json[0] or json[1] etc.

比如json[0]或json[1]等等。

#5


0  

json_encode rulez when you need this stuff.

当您需要这些东西时,json_encode rulez。

I recently learned this cool thing too! Here's how you do it:

我最近也学到了这个很酷的东西!你可以这样做:

function jsonResponse($array) {
     header('Content-type: application/json; charset=utf-8;');
     die(json_encode($array));
}

This is optional, if you want to do it, you don't have to, but in my MVC system, I tend to write this way... So first I make an ajax request (prototype), to a script, that later calls this function jsonResponse I mentioned earlier...

这是可选的,如果你想这么做,你不必这么做,但是在我的MVC系统中,我倾向于这样写……因此,我首先向脚本发出ajax请求(原型),然后调用我前面提到的这个函数jsonResponse…

    new Ajax.Request('URL',
{
    method:'post',
    onSuccess: function(transport){
        res = transport.responseJSON;
        $('actionInformation').update(res.username);
    },
    onFailure: function(){
        alert('Something went wrong...')
    }
});

This is the jscript code, notice the res.msg, this is where we can operate with array. But, be sure to send response in JSON format in your PHP, using the jsonResponse function, it's easy to use, e.g., your php function can look something like this :

这是jscript代码,注意res.msg,这是我们可以使用数组进行操作的地方。但是,一定要在PHP中以JSON格式发送响应,使用jsonResponse函数,它很容易使用,例如,您的PHP函数可以如下所示:

function ajax_get_user() {
     $userName = 'Adrian';
     $active = 1;
     jsonResponse(array('username' => $username, 'active' = $active));
}

Later you can get it easy, res.username, res.active.

稍后你就可以轻松地得到,res.username, res.active。

I think this should do it!

我认为应该这样做!

#1


20  

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:

在PHP方面,您需要打印:

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

#2


8  

I made an array $result in PHP and at the end of request.

我在PHP和请求结束时创建了一个$result数组。

 echo json_encode($result); 

and in JS $.post handler function :

在JS美元。邮政处理函数:

var obj = $.parseJSON(data);
var v = data.k; 

where k is key value in associative array.

其中k是关联数组中的键值。

#3


2  

json_encode is definitely the way to go. jQuery even has built-in support for parsing JSON. You could use e.g.

json_encode一定是可行的。jQuery甚至还内置了解析JSON的支持。你可以使用。

$.ajax({
    url: "<?php echo site_url('demo/getPhotos/'); ?>",
    type: 'POST',
    data: form_data,
    dataType: 'json', // will automatically convert array to JavaScript
    success: function(array) {
        alert(array[0]); // alerts first string
    }
});

#4


0  

return the json itself and then construct the array in js by looping over the json as follows:

返回json本身,然后在json上循环构建js中的数组,如下所示:

var array=[];
for(var key in json)
{    
    if(json.hasOwnProperty(key))
      array.push(json[key]);
}

Or you can simply work with the json itself any reason for needing the array?

或者,您可以简单地使用json本身,有什么理由需要这个数组吗?

something like json[0] or json[1] etc.

比如json[0]或json[1]等等。

#5


0  

json_encode rulez when you need this stuff.

当您需要这些东西时,json_encode rulez。

I recently learned this cool thing too! Here's how you do it:

我最近也学到了这个很酷的东西!你可以这样做:

function jsonResponse($array) {
     header('Content-type: application/json; charset=utf-8;');
     die(json_encode($array));
}

This is optional, if you want to do it, you don't have to, but in my MVC system, I tend to write this way... So first I make an ajax request (prototype), to a script, that later calls this function jsonResponse I mentioned earlier...

这是可选的,如果你想这么做,你不必这么做,但是在我的MVC系统中,我倾向于这样写……因此,我首先向脚本发出ajax请求(原型),然后调用我前面提到的这个函数jsonResponse…

    new Ajax.Request('URL',
{
    method:'post',
    onSuccess: function(transport){
        res = transport.responseJSON;
        $('actionInformation').update(res.username);
    },
    onFailure: function(){
        alert('Something went wrong...')
    }
});

This is the jscript code, notice the res.msg, this is where we can operate with array. But, be sure to send response in JSON format in your PHP, using the jsonResponse function, it's easy to use, e.g., your php function can look something like this :

这是jscript代码,注意res.msg,这是我们可以使用数组进行操作的地方。但是,一定要在PHP中以JSON格式发送响应,使用jsonResponse函数,它很容易使用,例如,您的PHP函数可以如下所示:

function ajax_get_user() {
     $userName = 'Adrian';
     $active = 1;
     jsonResponse(array('username' => $username, 'active' = $active));
}

Later you can get it easy, res.username, res.active.

稍后你就可以轻松地得到,res.username, res.active。

I think this should do it!

我认为应该这样做!