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

后端 未结 5 1373
执笔经年
执笔经年 2020-12-03 07:33

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 Aja

5条回答
  •  青春惊慌失措
    2020-12-03 08:27

    json_encode rulez when you need this stuff.

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

        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 :

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

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

    I think this should do it!

提交回复
热议问题