Passing array through AJAX from php to javascript

前端 未结 3 1636
青春惊慌失措
青春惊慌失措 2021-01-20 02:26

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database. I take the values from the db with this code (file.php):

相关标签:
3条回答
  • 2021-01-20 02:46

    use this

    echo json_encode($array);
    

    on server side

    and

    var arr=JSON.parse(result);
    

    on client side

    0 讨论(0)
  • 2021-01-20 02:51

    You need to convert the php array to json, try:

    echo json_encode($array);

    jQuery should be able to see it's json being returned and create a javascript object out of it automatically.

    $.post('./file.php', function(result)
    {    
         $.each(result, function()
         {
             console.log(this.Latitude + ":" + this.Longitude);
         });
    });
    
    0 讨论(0)
  • 2021-01-20 03:01

    As Ruslan Polutsygan mentioned, you cen use

    echo json_encode($array);
    

    on the PHP Side.

    On the Javascript-Side you can simply add the DataType to the $.post()-Function:

    $.post(
      './file.php',
      function( result ){    
        console.log(result);
      },
      'json'
    );
    

    and the result-Parameter is the parsed JSON-Data.

    You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:

    header('Content-type: application/json');
    

    See
    http://api.jquery.com/jQuery.post/
    http://de3.php.net/json_encode

    0 讨论(0)
提交回复
热议问题