通过单击 HTML 按钮执行服务器端代码的最简单方法
Easiest way to execute server side code via a HTML button click
单击 HTML
按钮在网络服务器上执行代码的最简单方法是什么?例如,我想要一个 Raspberry Pi
运行 Apache
来呈现一个带有按钮的网页,每个按钮都应该能够被按下,然后在 [=14= 上执行系统命令]. Pi
在本地会是 运行 所以我不关心安全等问题
我对网络编程知之甚少,看过很多建议,例如PHP
与 HTML
、jQuery
和 AJAX
但我只需要一个简单的解决方案。
学习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 按钮点击调用
$.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
},
})
在你的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');
?>
单击 HTML
按钮在网络服务器上执行代码的最简单方法是什么?例如,我想要一个 Raspberry Pi
运行 Apache
来呈现一个带有按钮的网页,每个按钮都应该能够被按下,然后在 [=14= 上执行系统命令]. Pi
在本地会是 运行 所以我不关心安全等问题
我对网络编程知之甚少,看过很多建议,例如PHP
与 HTML
、jQuery
和 AJAX
但我只需要一个简单的解决方案。
学习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 按钮点击调用
$.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
},
})
在你的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');
?>