Passing PHP JSON to [removed] echo json_encode vs echo json declaration

后端 未结 9 2245
猫巷女王i
猫巷女王i 2021-01-05 01:52

I\'m trying to create a common constants file to share between php and javascript, using JSON to store the constants. But I\'m wondering why pass the JSON from PHP to javasc

9条回答
  •  旧时难觅i
    2021-01-05 02:07

    It all depends on what you want to send from server to the client - be it a data (JSON) or some code.

    Two approaches:

    1. Echo a JSON file on a server - then you print your JSON document and set response Content-Type to application/json. This way you can use any AJAX library you wish, like $.get or raw XMLHttpRequest etc. It is a way of passing data.

    2. Echo a Javascript code on a server and then use $.getScript to load it. It's a way of passing code. This is potentially less secure, because your code can contain not only JSON, but also any arbitary code. So if attacker can compromise your server, he could be able to push code to any client for a remote execution.

    If you want to pass data only, go with first approach. It's cleaner and more safe.

    Additionally, if you ever end up writing frontend in different environment, say different programming language, you'll be able to resuse the same JSON-returning endpoint. It'll be harder if you return Javascript code.

提交回复
热议问题