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

前端 未结 5 1347
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 23:11

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 a

5条回答
  •  庸人自扰
    2020-12-09 23:51

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

提交回复
热议问题