【问题标题】:Easiest way to execute server side code via a HTML button click [closed]通过 HTML 按钮单击执行服务器端代码的最简单方法 [关闭]
【发布时间】:2016-12-15 12:23:37
【问题描述】:

单击HTML 按钮在网络服务器上执行代码的最简单方法是什么?例如,我想要一个运行Apache 的Raspberry Pi 来呈现一个带有按钮的网页,每个按钮都应该能够被按下,然后在Pi 上执行系统命令。 Pi 将在本地运行,所以我不关心安全等问题。

我对 Web 编程知之甚少,但看过很多建议,例如PHP 与 HTML、jQuery 和 AJAX 但我只需要一个简单的解决方案。

【问题讨论】:

  • 在按钮按下时使用 Ajax 调用,这样您就可以运行您的服务器代码。

标签: php html button webserver


【解决方案1】:

在你的 html 中

<a href="#" onclick="ajaxcall()">Button</a>

在你的 js 中(使用 jquery)

function ajaxcall() {
   $.ajax({
        type: "POST", 
        url: "myscript.php",  
        data: {
            var1  :val1
        },
        success: function(response){
            // do something
        }
    })
}

在你的 php 中

<?php
echo exec('your server command to exec');
?>

【讨论】:

  • 我尝试过这种方式,但服务器上没有执行任何操作。当我单击该按钮时,服务器应设置与另一台设备的 TCP 连接,但事实并非如此。有什么想法吗?
  • 警报中发生的所有事情都会弹出“”,但 netcat 从未真正运行过
  • 工作中,没有安装 PHP...
【解决方案2】:

学习 AJAX,非常简单。

例如:

$(document).ready(function(){
    $('#btn').click(function(){    // this ajax will call on button click whose id is "btn"
        $.ajax({
            url: 'process.php',   // url of file                     
            type: 'POST',         // get or post                         
            data: {
                var1  :val1,     // variables list (key-value pair) 
                var2  :val2
            },
            success: function(response){    // response from process.php
                // do your stuff here
            }
        });
    });
});

P.S.不要忘记包含来自 CDN 或本地的 jquery 库

Ajax Reference

【讨论】:

  • 我对网络编程知之甚少,所以这个答案对我来说太复杂了,无法使用
【解决方案3】:

您可以在按钮单击时添加 ajax 调用

$.ajax(function(){
      url : 'demo.php', //server  script (php) return json/html response
      method:'POST',
      data:'{key : value}' , //parameter you need tosend
     dataType:'json',// return type html/json
     success:function(res){
         console.log(res); //res contains result 
        //you can user result as you want
     },
     error:{
        //error message
    },

})

【讨论】:

    猜你喜欢
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    • 2021-03-24
    • 2012-06-27
    • 2011-07-09
    • 2020-11-20
    相关资源
    最近更新 更多