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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7263052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:32:36  来源:igfitidea点击:

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

phpjavascriptjqueryajaxjson

提问by Joe W

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 获取一组照片,然后我希望将其附加到<div>我的页面上的空白处。

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.

如果我只是echo $photos;将数据发送到成功回调,但它似乎不是可用的格式。

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

如果我var_dump($photos)在 PHP 中执行 a ,结果如下所示:

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_encodeand 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 的最佳方法是什么?

回答by Richard

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

回答by bboydev

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

$result在 PHP 中创建了一个数组,并在请求结束时。

 echo json_encode($result); 

and in JS $.posthandler function :

并在 JS$.post处理函数中:

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

where kis key value in associative array.

k关联数组中的键值在哪里。

回答by pimvdb

json_encodeis 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
    }
});

回答by Baz1nga

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] 之类的东西。

回答by Adrian

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!

我觉得这个应该可以!