prevent整个PHP执行的Ajax请求prevent、PHP、Ajax

2023-09-10 21:47:45 作者:■ 相见恨晚

我有一个AJAX脚本(jQuery的),要求index.php来输出生成的变量。此的index.php也是其中产生整页,最初填充数据的文件。我怎么能只让getNewData()函数时,Ajax请求此文件。现在,它复制了整个页面,并输出其所以有是二的一切。

I have an ajax script (jquery) that asks index.php to output generated variables. This index.php is also the file where the whole page is generated and initially populated with data. How can I only let the getNewData() function when ajax requests this file. Right now it duplicates the entire page and outputs it so there is two of everything.

推荐答案

本机PHP实现Dooltaz的回答会是如下:

A native PHP implementation of Dooltaz's answer would be as follows:

function isAjax() {
    return $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest";
}

当然,

这是偶然的 X_Requested_With 头居然被送到了客户XHR请求。据我所知,所有主要的JavaScript库做包括这个头,但如果你滚动你的XHR实现,你需要添加它。

This of course, is contingent on the X_Requested_With header actually being sent by the clients XHR request. As far as I know, all major Javascript libraries do include this header, but if you're rolling on your XHR implementation, you'll need to add it.