PHP check whether Incoming Request is JSON type

2019-01-27 20:25发布

Is there anyway to check whether an incoming request is of AJAX JSON type?

I tried

if(($_SERVER['REQUEST_METHOD']=='JSON'))
{
}

But it didn't work.

Any thoughts?

6条回答
老娘就宠你
2楼-- · 2019-01-27 21:00

You can do a check on the accept param, if it's text/javascript your talking json, if it's text/xml guess what :P

$_SERVER['HTTP_ACCEPT']

查看更多
3楼-- · 2019-01-27 21:05

you can always set an extra header specifying that, or use an arbitrary variable to indicate JSON requests.

查看更多
Emotional °昔
4楼-- · 2019-01-27 21:09

Try json_decode()

查看更多
放荡不羁爱自由
5楼-- · 2019-01-27 21:11

You can check the X-Requested-With header, some libraries, like jQuery set it to "XMLHttpRequest".

$isAjaxRequest = $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest';
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-27 21:16

Where are you accepting requests from, exactly, that you wouldn't know?

You could have a function at the beginning of the script that tries to import the data as JSON or simplexml. If it catches an error, you know it's the other one...

On second thought, have it test it to be JSON, simplexml will throw an error for tons of reasons.

 $json_request = (json_decode($request) != NULL) ? true : false;
查看更多
Explosion°爆炸
7楼-- · 2019-01-27 21:17

You would need to set a header from the client side. jQuery and other libraries set a x-requested-with header:

if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
   echo "Ajax request";
}
查看更多
登录 后发表回答