简体   繁体   English

将JSON从PHP传递到JavaScript(以隐藏Steam WEB API密钥)

[英]Passing JSON from PHP to JavaScript ( to hide Steam WEB API Key )

I want to use the Steam WEB API to generate some stats about games. 我想使用Steam WEB API生成一些有关游戏的统计信息。 In order to use the Steam WEB API I have to use a key that I am supposed to hide. 为了使用Steam WEB API,我必须使用我应该隐藏的密钥。 I want to do all of the data processing with JavaScript, which doesn't allow me to hide the key. 我想用JavaScript进行所有数据处理,这不允许我隐藏键。 So I came up with this solution. 所以我想出了这个解决方案。 I query the database in php, and pass the JSON object to JavaScript. 我在php中查询数据库,并将JSON对象传递给JavaScript。 My question is whether or not this is the preferred or best way to do this. 我的问题是,这是执行此操作的首选还是最佳方法。

PHP: PHP:

<?php
$matchDetailsUrl  = "https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/? match_id=<MATCHID>&key=<KEY>";
$matchDetailsRaw  = file_get_contents($matchDetailsUrl);
$matchDetailsJson = json_decode($matchDetailsRaw);
?>

JavaScript: JavaScript:

<script>
var obj = JSON.parse('<?php echo json_encode($matchDetailsJson) ?>');
console.log(obj);
</script>

There should be no need to re-encode all of the JSON data retrieved from the PHP file decode for JavaScript handling. 无需重新编码从PHP文件解码中检索到的所有JSON数据以进行JavaScript处理。 You can write your JavaScript functions to do what they need to by passing results from the PHP decode, and call the JavaScript functions with PHP. 您可以通过传递来自PHP解码的结果来编写JavaScript函数以执行所需的功能,然后使用PHP调用JavaScript函数。

<?php
    echo "<script>functionName(" . $parameter1 . ", " . $parameter2 . ");</script>";
?>

Assuming $parameter1 and $parameter2 are PHP variables you made with some of the decoded JSON data from the API call, the page's HTML source will display this like a standard JavaScript function call with hard coded variable parameters being passed. 假设$ parameter1和$ parameter2是您使用API​​调用中的某些解码的JSON数据创建的PHP变量,则页面的HTML源代码将像标准JavaScript函数调用一样显示此信息,并传递了硬编码的变量参数。

Your JavaScript function can do what it needs to do with the parameters given to it. 您的JavaScript函数可以使用为其提供的参数来完成所需的工作。

If your data handling is a "render once" type of affair, I would recommend writing the data handling functions in PHP rather than JavaScript to eliminate the confusion, but you can definitely pass what you need, as you need it between the PHP and JavaScript with out sending all the data. 如果您的数据处理是“一次渲染”的事情,我建议您使用PHP而不是JavaScript编写数据处理函数,以消除混淆,但是您绝对可以在PHP和JavaScript之间传递所需的信息无需发送所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM