简体   繁体   English

如何从HTML页面获取Javascript变量?

[英]How to get Javascript variable from an HTML page?

In the source code of a page on the internet, there is a Javascript variable containing JSON data that I would like to store in a variable in my PHP program. 在互联网页面的源代码中,有一个Javascript变量,它包含要存储在我的PHP程序的变量中的JSON数据。

Any idea about how to do it? 关于如何做的任何想法?

The file is on a public html link and it looks like this: 该文件位于公共html链接上,如下所示:

<script type="text/javascript">
    var serializedForm = {"fields": ... } ;
</script>

Thank you for your time and answers :). 谢谢您的时间和答复:)。

Your use of the words "a page on the Internet" and "public" makes me think that you didn't write the page and that you only have access to the source code. 您对“ Internet上的页面”和“公共”这两个词的使用使我认为您没有编写该页面,而您只能访问源代码。 In that case you might have to retrieve the variable as plain text and then parse it as JSON. 在这种情况下,您可能必须以纯文本形式检索变量,然后将其解析为JSON。

First get the page content as plain html 首先获取页面内容为纯HTML

$html = file_get_contents($yourURL);

Then find the line you are looking for 然后找到您要寻找的线

$javascriptVar = preg_grep("/var serializedForm = {.*}/", $html);

This should get you the entire JSON variable as well as the assignment part ( var serializedForm = ). 这将为您提供整个JSON变量以及分配部分( var serializedForm = )。

Get rid of it by either running another regex match or manually counting the amount of characters to remove and then parse your variable. 通过运行另一个正则表达式匹配项或手动计算要删除的字符数量然后解析变量来摆脱它。

$result = json_decode($javascriptVar);

Okay If you want to store that javascript variable in PHP then, you might have to send that variable to any PHP file using GET or POST method with ajax. 好的,如果您想在JavaScript中存储该javascript变量,则可能必须使用带有ajax的GET或POST方法将该变量发送到任何PHP文件。

you can send the var serializedForm = {"fields": ... } ; 您可以发送var serializedForm = {"fields": ... } ; in ajax as a post or get method and in ajax.php file get this variable under $_POST or $_GET and save it to php variable. 在ajax中作为post或get方法,在ajax.php文件中,在$_POST or $_GET下获取此变量,并将其保存到php变量中。

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

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