当我点击表单上的提交时,我正试图在我的网页上输出我的bash脚本。目前,我可以看到我的脚本在点击时成功执行,但这会将我带到另一个页面。我希望它在同一页面上返回输出。
HTML:
<form action="testexec.php" method="post">
<label class="col">Up/down</label>
<span class="col">
<input type="radio" name="option" id="r1" value="1" />
<label for="r1">Up</label>
<input type="radio" name="option" id="r2" value="2" />
<label for="r2">Down</label>
</span>
<span class="col">
<input type="submit" class="button"/>
</span>
</form>
testexec.php:
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['option']) && $_POST['option'] == 1)
{ $output = shell_exec("/var/www/html/testscripts/up.sh");}
if(isset($_POST['option']) && $_POST['option'] == 2)
{ $output = shell_exec("/var/www/html/testscripts/down.sh");}
//header('Location: http:/mydirectory/systemTest.php?success=true');
echo "<pre>$output</pre>";
}
?>
up.sh
#!/bin/bash
touch /tmp/testfile
ls -ltr /tmp
echo "I am Up"
我试图做以下事情,但它不起作用:
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$.ajax({
url:"testexec.php",
type: "POST",
success:function(result){
alert(result);
}
});
});
})
</script>
答案 0 :(得分:1)
按照以下内容编辑<script>
(我假设您使用的是jQuery,基于示例代码):
<script type="text/javascript">
// Removed $(document).ready(), as this is a deprecated method as of jQuery 3.0 and is not the best practice. Especially for this script, it is not needed at all - AJAX is triggered upon button press, not upon loading
// Changed "button" to ".button" to correctly select the pressed input button
$(".button").click(function(event){
// Prevent the default HTML form submission from going ahead - for our purposes, this stops the page from navigating away
event.preventDefault();
$.ajax({
url:"testexec.php",
type: "POST",
// Have to send the option number with the POST request - the backend is expecting a $_POST['option'] number. In AJAX, this is done with 'data'
data: {option: $('input[type=radio]:checked').val()},
dataType: "text",
success:function(result){
alert(result);
}
});
});
</script>
有关上述内容的更多信息:
$(document).ready()
已弃用且应避免使用:https://api.jquery.com/ready/ .class
选择器如何工作:https://api.jquery.com/class-selector/ event.preventDefault()
:https://api.jquery.com/event.preventdefault/ 答案 1 :(得分:-1)
我是否可以建议您更改HTML文件(名为.php,而不是.html),如下所示,不需要AJAX脚本。这将重新加载当前页面并在<form>
:
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['option']) && $_POST['option'] == 1)
{ $output = shell_exec("/var/www/html/testscripts/up.sh");}
if(isset($_POST['option']) && $_POST['option'] == 2)
{ $output = shell_exec("/var/www/html/testscripts/down.sh");}
}
?>
<form action="" method="post">
<label class="col">Up/down</label>
<span class="col">
<input type="radio" name="option" id="r1" value="1" />
<label for="r1">Up</label>
<input type="radio" name="option" id="r2" value="2" />
<label for="r2">Down</label>
</span>
<span class="col">
<input type="submit" class="button"/>
</span>
</form>
<?php
echo "<pre>" . ( ($output) ?: '' ) . "</pre>";
?>