gpt4 book ai didi

php - 通过 Javascript 在服务器上调用 PHP?

转载 作者:可可西里 更新时间:2023-10-31 22:58:33 26 4
gpt4 key购买 nike

我正在尝试制作一个非常简单的网页,当我点击一个按钮时它就会执行一些操作。

我正在尝试使用 Javascript,这样我就不必重新加载主页或任何东西。

所以我想要一个显示“Shutdown”的按钮,我只想运行 shutDown.php,它会在我单击它时关闭服务器。

我已经搜索了一个小时,但找不到一个简单的示例。有人可以发布一个非常简单的示例或一个链接吗?

非常感谢:)

编辑:好的,这是我可怜的尝试..它不起作用..有什么提示吗?

<html>
<head>
<title>Control Page</title>
</head>

<body>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript">
/*************************************
JQUERY EXAMPLE
*************************************/
$('#mysubmit').click(){
var jqueryXHR = $.ajax({
'type': 'POST',
'url': 'http://localhost/killIE.php',
'dataType': 'json'
});
}
}
</script>

<input type="submit" name="mysubmit" value="Click!" />


</body>
</html>

最佳答案

是的 - 称为 AJAX 的技术。您可以使用原始 javascript 编写它,也可以使用现成的库。现在(主观上)最流行的 JS 库是 jQuery,我将在示例中使用它。

注意:这将在服务器上触发您的 shutDown.php PHP 脚本,而无需重新加载页面。但是 - 在关闭服务器后,您显然无法解析 Web 请求 :)...

/*************************************
JQUERY EXAMPLE
*************************************/
$('#myShutdownButton').click(){
var jqueryXHR = $.ajax({
'type': 'GET',
'url': 'http://someServer.com/shutDown.php',
'data': {'shutdownServer': 'yes'},//optional
'dataType': 'json'
});
}
}

附言我假设您知道必须首先在 html 文件头中加载 jQuery 库,如下所示:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

然后将 jquery 代码放在脚本标签中:

<script>
...that jQuery code...
</script>

按要求更新 - 完整的脚本版本

<html>
<head>
<title>Control Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script>
//we need document.ready call to make sure that DOM loaded before we try to bind anything
$(document).ready(function() {
//Here we bind click event
$('#mysubmit').bind('click', function(e){e.preventDefault();
//This is what happens on click - we send AJAX request
var jqueryXHR = $.ajax({
'type': 'POST',
'url': 'http://localhost/killIE.php',
'dataType': 'json'
});
//And when AJAX requests complete(succeeded or failed) - we update text
jqueryXHR.complete(function(){
$('span#result').html('Oh no!!! the End is neearh! erver is shutting DoWn.')
});
})
});
</script>
</head>
<body>
<input type="submit" id="mysubmit" value="Kill da server!" style = "margin-left:100px; margin-top:100px;" />
<br/>
<br/>
<br/>
<span id = "result">Not clicked yet - good!</span>

</body>
</html>

关于php - 通过 Javascript 在服务器上调用 PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com