我试图通过使用ajax的html按钮调用PHP函数,所以我不必刷新页面。 PHP函数关闭IP电源板上的插座并且没有返回值,我已经确认PHP函数也不是问题。我不确定我的ajax语法是否不正确或者我的php代码中是否需要GET方法。任何帮助表示赞赏!
<?php
$fp = fsockopen("epdl-ps1.bucknell.edu", 23, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "\$A3 1 0\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
}
?>
<div class="outlet1off">
<a href="#" onsubmit="outlet1off()" id="outlet1off" class="outlet1off">Off</a>
<script>
function outlet1off(){
$.ajax({
url: "localhost/EPDL%20Control%20Page/outlet1off.php",
type: "GET",
datatype:"html"
});
};
</script>
</div>
答案 0 :(得分:0)
使用onclick
代替onsubmit
:
<a href="#" onclick="outlet1off()" id="outlet1off" class="outlet1off">Off</a>
修改强>
另请注意,您的网址不是有效网址。尝试:
url: "http://localhost/EPDL%20Control%20Page/outlet1off.php",
或
url: "/EPDL%20Control%20Page/outlet1off.php",
答案 1 :(得分:0)
更简单的代码版本。您需要使用点击事件而不是提交:
$('#outlet1off').click(function() {
$.get('/EPDL%20Control%20Page/outlet1off.php');
});
如果您需要处理返回的数据(错误处理),可以向.done
添加.always
或$.get
。见https://api.jquery.com/jquery.get/