Inserting php into js file

前端 未结 5 1003
遇见更好的自我
遇见更好的自我 2021-01-15 01:40

I have a loading gif for the gallery on my website. In my js file I have this code to show the loader:

image: $(\"\"),         


        
5条回答
  •  别那么骄傲
    2021-01-15 02:18

    I prefer to..

    1) In my header include (the php include that contains any data), write a small inline JS function that creates a global object containing any variables I need from the server (PHP). I can use the 'echo' and 'json_encode' functions here because its in an inline JS snippet in a php file.

    2) You could write a JS function inside your JS file that uses AJAX to call a PHP file, which will return the same JSON encoded data as number 1, then you parse it and assign in to a global variable.

    Both essentially do the same thing, except with 2 you are using AJAX, which will add an additional request. I prefer option 1, because it is done along with the pages execution. Option 2 may require you to wait until the DOM is ready, depending on various aspects of your program (in which I can not tell).

    Option 1 requires inline JS, but you really shouldn't harp on this, as with dynamic websites it can actually be a plus, as along as it is short and concise. Some people get on others about inline JS. Don't let them yell at you.

提交回复
热议问题