检测一个Ajax请求 [英] Detect an ajax request
问题描述
我在写我自己的MVC框架,实践,我有一个请求类。我想搭上相应的请求的类型和分析数据是否它的一个AJAX / JSON来电或HTML / XML请求。
I'm writing my own MVC framework to practice and I have a Request class. I would like to catch the type of request and parse data accordingly whether its an AJAX/JSON call or a HTML/XML request.
即时通讯目前使用的:
$_SERVER['HTTP_ACCEPT']
和使用时的var_dump它返回上面的应用程序/ JSON 作为这样的:
and above when used var_dump on it returns application/json for this:
$.ajax({
type: 'post',
url: 'index',
dataType: 'json',
data: {
_method: 'put'
}
});
的var_dump($ _ SERVER ['HTTP_ACCEPT'])的回报:
string(46) "application/json, text/javascript, */*; q=0.01"
问: 是这种方法可靠吗?是否总是工作?是否有像这样的检测Ajax调用?
Question: is this method reliable? Does it work always? Are there any security problems with detecting ajax call like this?
请注意,在我的框架,我所有的Ajax调用必须有数据类型:JSON,除非它是一个不同的呼叫类型例如 HTML 或 XML 。
Note that all my ajax calls in my framework must have dataType: 'json' unless its a different type of call like HTML or XML.
推荐答案
使用jQuery,您可以使用 $ _ SERVER ['HTTP_X_REQUESTED_WITH']
将被设定为XMLHtt prequest。这是使用jQuery的时候,最可靠的方法。
Using jQuery, you can use $_SERVER['HTTP_X_REQUESTED_WITH']
which will be set to "XMLHttpRequest." This is the most reliable method when using jQuery.
这篇关于检测一个Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!