How to return an array from an AJAX call?

前端 未结 6 1413
猫巷女王i
猫巷女王i 2020-12-02 06:13

I\'m searching for a better solution to making an AJAX call with jQuery, having the PHP file return an array, and have it come out client-side as a Javascript array. Here is

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 07:16

    Use JSON to transfer data types (arrays and objects) between client and server.

    In PHP:

    • json_encode
    • json_decode

    In JavaScript:

    • JSON.stringify
    • JSON.parse

    PHP:

    echo json_encode($id_numbers);
    

    JavaScript:

    id_numbers = JSON.parse(msg);
    

    As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

    id_numbers = new Array();
    $.ajax({
        url:"Example.php",
        type:"POST",
        success:function(msg){
            id_numbers = msg;
        },
        dataType:"json"
    });
    

提交回复
热议问题