检测一个ajax请求

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.

Im currently using:

$_SERVER['HTTP_ACCEPT']

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']) returns:

string(46) "application/json, text/javascript, */*; q=0.01"

Question: is this method reliable? Does it work always? Are there any security problems with detecting ajax call like this?

Note that all my ajax calls in my framework must have dataType: 'json' unless its a different type of call like HTML or XML.

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.

Colin Morelli answered your main question, but this should help you with your follow ups.

XMLHttpRequest means its an ajax call? How would I detect the type if its XML or JSON

Yes. XMLHttpRequest is JavaScript object that makes the request. It's poorly named now, though, because you can have it send whatever you want. To answer your second question you'll have to do some sort of parsing attempt on the payload you receive. You can scan for XML and if not found just assume it's JSON and attempt to parse.