开发者

How to pass an array of strings from PHP to Javascript using $.ajax()?

I have a PHP script that retrieves names (strings) from database. I would like to pass this array to Javascript using $.ajax(). I cannot understand how should I encode the array in PHP and then decode it in Javascript. Could someone give an example code for 开发者_开发百科this ? Thanks a lot !!


<?php // test.php
$myArray = array(1, 2, 3);
echo json_encode($myArray);
?>

HTML File:

$(function() {
    $.getJSON('http://localhost/test.php', function(data) {
        $(data).each(function(key, value) {
            // Will alert 1, 2 and 3
            alert(value);
        });
    });
});


u can use json_encode

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>

full example you can read at :

http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/

or

http://www.prodevtips.com/2009/12/09/multiple-select-lists-with-jquery-and-json/


<?php
    echo json_encode(array('key' => 'value', 'cool' => 'ice'));
?>

json is a javascript object. So there is no need to "decode" it. However, it looks like you are using jquery. There is a nifty function for retrieving json data:

jQuery.getJSON(url, senddata, function(returndata){alert(returndata.cool);})

or

jQuery.getJSON(url, senddata, function(returndata){mybigfunction(returndata);})

mybigfunction(data)
{
    myvar = data.cool;
    alert(myvar);
}

http://api.jquery.com/jQuery.getJSON/

or you could also do it with $.ajax as you mentioned:

jQuery.ajax({
    url: url,
    dataType: 'json',
    data: senddata,
    success: function(data){mybigfunction(data)}
});

mybigfunction(data)
{
    myvar = data.cool;
    alert(myvar);
}

http://api.jquery.com/jQuery.ajax/

The "callback" is a function that gets called and passed the json data returned from the url.

You will 'ice' baby... ermm... sorry for the corn.

The getJSON method is rather short and handy. Have a look at the links for more details.


This is Php File Code

<?php
$array = array(1, 2, 3);
echo json_encode($array);
?>

Then you can parse $array in your $.ajax() like this

success: function (data) {
            var x = JSON.parse(data);
            console.log(x);
        }


To do this, you'll just have to echo out a script into the PHP page that contains your data, which you can then access from any other Javascript on the page, including jQuery and .ajax().

Again, if you just want to pass it via an AJAX call, just use json_encode():

<?php
echo json_encode(
 array(
  'groupidlist'=>$groupids,
  'groupnamelist'=>$groupnames,
  'serverurl'=>$serverurl,
  'uid'=>$curuser->getID()
 )
);
?>

And then process it with the callback functions from .ajax() or, probably better, .getJSON(), which is built for just this use.

I promise I don't just spam my blog here, but I wrote a post on passing variables between Javascript and PHP, because I did it often enough that I came up with a simple/reliable/clean and reusable way to do so. If you're regularly passing data from PHP to Javascript and don't need AJAX, I'll paste the essentials here:

At the top of each external js file, I add comments as to which PHP variables are required, so I can keep track of what I need when I include it (this is optional, of course, but nice):

/* This script depends on the following variables in phpvars:
groupidlist
groupnamelist
serverurl
uid
*/

Then, in the PHP file, I pass the needed variables with a single line of Javascript, assigning a JSON Array with all the needed values. Examples in PHP, directly from my code:

<script type="text/javascript">
 var phpvars = <?php
echo json_encode(
 array(
  'groupidlist'=>$groupids,
  'groupnamelist'=>$groupnames,
  'serverurl'=>$serverurl,
  'uid'=>$curuser->getID()
 )
);
   ?>;
</script>

Once that is set up, I can then simply access whatever PHP Variables I need in the Javascript through the phpvars array. For example, if I needed to set an image source using my serverurl, I could do as follows:

imgElement.src = phpvars.serverurl + '/images/example.png';

Because it uses JSON, there is no worrying about making sure that you don't screw anything up in your Javascript by trying to insert the PHP variables. The encoding/decoding of the variables is handled on both ends by built-in JSON functions, so it is very hard to break it, and brainless to pass variables - you pass them like you would any other PHP array. In my fiddling that led to this, I had problems with both of these, and this solution takes care of them nicely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜