我如何使用 Ajax 检查按钮是否被点击?我想要一个按钮,在单击时发送 Ajax 请求(已经完成),并在单击按钮时收到通知。我只是不知道如何检查它是否是从另一个源文件中按下的,以及在 Ajax 请求中发送什么 header 。我的代码如下(假设我的表单中有一个名为“button”的按钮:
<script type = "text/javascript">
function checkVote()
{
request = new ajaxRequest();
request.open("POST", "checkButton.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
}
function ajaxRequest()
{
try
{
request = new XMLHttpRequest();
}
catch(e1)
{
try
{
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e2)
{
try
{
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e3)
{
request = false;
}
}
}
return request;
}
</script>
最佳答案
所有流行的 JavaScript 库/框架都会发送值为 XMLHttpRequest
的 HTTP_X_REQUESTED_WITH
,让您的脚本知道请求是通过 Ajax 发出的。因此,如果您使用 jQuery、Prototype 等,这将为您处理(并使您的 JavaScript 编码生活更轻松)。如果没有,您可以自己设置,以便遵循公认的惯例。
if ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
// Ajax request
}
关于php - 使用 Ajax 检查按钮是否被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11255008/