How can I populate a javascript array with values from a database using PHP?

后端 未结 5 860
走了就别回头了
走了就别回头了 2021-01-03 14:59

I have to create a javascript array whose elements are fetched by php from a database. Is it possible? If so, how?

(I dont want to use ajax to do that)

5条回答
  •  走了就别回头了
    2021-01-03 15:32

    If you can loop through the database contents, creating an array is simple:

    echo "var myArray = [";
    

    Loop through array here and add commas to separate values.

    echo "];";
    

    Your myArray variable will be available client-side. It should look something like:

    var myArray = [1, 3, 2, 4];
    

    Alternatively and to avoid an extra comma due to loop-based string concatenation, you can write the variable to the client as follows:

    echo "var myArray = [];"
    

    ...and do the following for each data row:

    echo "myArray.push($db_data);"
    

    This is effective, though not quite as clean as the previous approach. You will end up with code similar to the following:

    var myArray = [];
    
    myArray.push(3);
    myArray.push(5);
    myArray.push(1);
    
    alert(myArray); // will display "3, 5, 1"
    

    My apologies for not being too familiar with PHP, but this is something that can be done with any server-side language.

提交回复
热议问题