在PHP中检测Ajax [英] Detect Ajax in PHP

查看:49
本文介绍了在PHP中检测Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ajax发布到同一php页面.

I am trying to make an ajax post to the same php page.

Ajax:

$("#loginForm").submit(function(e) {
    e.preventDefault();
    var postData = $(this).serialize();
    $.post("login.php", postData);
});

postData是正确的,并且采用以下格式:

The postData is correct and is in the following format:

username=john&password=123123

PHP(同一页):

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      echo 'Ajax Request Detected';
}

但是,如果此if-check始终返回false,则永远不会执行回显行.我在这里做什么错了?

However this if-check always returns false and the echo line is never executed. What am I doing wrong here?

推荐答案

这是在php中检测ajax请求的正确方法:

This is the correct way to detect ajax requests in php:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
    // this is ajax request, do something
}

这篇关于在PHP中检测Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆