【发布时间】:2016-12-14 11:40:09
【问题描述】:
我正在尝试将数据从我的 python 文件发送到 php 文件并在浏览器中显示。
我已阅读以下问题:Sending data using POST in Python to PHP,我的代码基于问题的答案。
到目前为止,我的 python 代码是:
import urllib2, urllib
def main():
mydata = [('one', '1'), ('two', '2')] # The first is the var name the second is the value
mydata = urllib.urlencode(mydata)
path = 'http://localhost/test2.php' # the url you want to POST to
req = urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
page = urllib2.urlopen(req).read()
print page
if __name__ == "__main__":
main()
我的php代码是:
<meta http-equiv="refresh" content="1" /> <!-- Updates the whole page each second -->
<?php
echo $_POST['one'];
echo "\n";
echo $_POST['two'];
?>
我正在更新页面,但它从未在浏览器中显示 1 和 2,它确实显示了用 python 打印的 1 和 2。有没有办法更新 php 文件,以便显示我发送给它的所有内容?
谢谢!
【问题讨论】:
-
你必须再回头看看事情是如何运作的。在 http 服务器环境中使用的 php 文件会将其输出发送到请求客户端。那是刷新页面视图的浏览器和来自该脚本的请求的 python 脚本。这两个不同的请求是完全独立的。没有任何机制可以使在一个脚本运行中使用的值神奇地出现在一个完全独立的脚本运行中。您很可能希望使用数据库来持久存储此类值。