运行通过AJAX传递的Python脚本的PHP命令按钮不起作用

2024-04-27 03:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍然在努力学习AJAX和各种实现方法。我在我的网站上有一个DIV标签,我使用AJAX在5秒后动态更新(定时更新是由于不相关的原因),通过重新加载状态.php文件放入DIV标记中。在

我遇到的问题是当我直接浏览状态.php命令按钮工作正常,但是当我通过索引.php他们没有回应。在

我想知道他们为什么会这样失败,以及我在工作中能以“ELI5”的方式做些什么。在

命令按钮运行一个Python脚本来打开/关闭车库门。下一次状态Python脚本(位于状态.php)当AJAX更新页面的这一部分时,它将拥有门的新状态,并最终在DIV标记中显示它。在

当我现在点击按钮的时候索引.php仍然显示在其中,但是DIV标记完全重新加载状态.php. 但是,当发生这种情况时,Python脚本似乎不会被触发。在

我怀疑命令按钮需要以更为AJAX/javaey的方式运行,而不是通过PHP,但我甚至不知道从哪里开始。在

哦,还有一件事:我还有一个CGI脚本(e.h.http://example.com/cgi-bin/myq-cgi.py?username=user&pass=pass&command=open),我也可以用它来开门/关门。我不使用它来显示状态,因为它不像完整的Python脚本那样包含状态上次更改的时间/日期。这可能是更好地打开/关闭门的一种潜在方法。在

在索引.php公司名称:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script type="text/javascript">
        $(function(){ 
            setInterval(function(){
                $.ajax({
                    url: "status.php",
                    type: "POST",
                    dataType: "text",
                    success: function(data){
                        $("#status_div").html('The Garage Door Status is: ' + data);
                    }
                })

            }, 5000);
        });
        </script>
    </head>
    <body>
        Somethign on the web page.  Normally this would be the main website while the DIV tag waits to load.
        <div id="status_div"></div>
    </body>
</html>

在状态.php公司名称:

^{pr2}$

Tags: text标记命令div脚本状态htmltype
1条回答
网友
1楼 · 发布于 2024-04-27 03:44:00

@hassan让我思考,所以我在索引.php所以它们不在ajax响应中。在

我让他们工作了。车库门开/关。这个索引.php在用户可以看到状态的地方快速地重新加载ajax,例如从Closed>;Open>;Closing>;Closing>;Closed。更重要的是,页面没有像旧的PHP按钮那样进行整体重新加载。在

这一次我用HTML/javascript代替PHP来做按钮。另外,我没有运行Python脚本,而是使用了一个不同的基于Python的CGI脚本,正如我在OP中提到的那样

一旦这个在索引.php,只是为了好玩,我把它复制到状态.php当它加载了ajax之后,它仍然可以在里面正常工作并且可以执行!在

这是javascipt第一次出现在索引.html,但最终转移到状态.php公司名称:

<script>
function open_door() {
    jQuery(function($) {
        $.ajax( {
            url : "http://example.com/cgi-bin/myq-cgi.py?user=somethibng@hotmail.com&pass=dfgsdfgsdfg&cmd=open",
            type : "GET",
            success : function(data) {
                alert ("Opening Door..."); //or use data string to show something else
                }
            });
        });
    }
</script>

<script>
function close_door() {
    jQuery(function($) {
        $.ajax( {
            url : "http://example.com/cgi-bin/myq-cgi.py?user=something@hotmail.com&pass=dfgdfgsdfg&cmd=close",
            type : "GET",
            success : function(data) {
                alert ("Closing Door..."); //or use data string to show something else
                }
            });
        });
    }
</script>


<form>
<input type="button" value="open" onClick="open_door()"
</form><form>
<input type="button" value="close" onClick="close_door()"
</form>

相关问题 更多 >