检查是否使用 Ajax 单击按钮


Checking if button is clicked with Ajax

我将如何检查是否使用 Ajax 单击了按钮?我想要一个按钮,当单击该按钮时,它会发送 Ajax 请求(已完成),并在单击该按钮时收到通知。 我只是不知道如何检查它是否是从另一个源文件按下的,以及在 Ajax 请求中发送哪些标头。 我的代码如下(假设我的表单中有一个名为"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库/框架都会发送值为XMLHttpRequestHTTP_X_REQUESTED_WITH,让您的脚本知道请求是通过Ajax发出的。因此,如果您使用 jQuery、Prototype 等,这将为您处理(并使您的 JavaScript 编码生活更轻松)。如果没有,您可以自己设置,以便遵循公认的约定。

if ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
  // Ajax request
}