PHP用于确定客户端请求的dataType或responseType

时间:2014-02-18 13:07:02

标签: javascript php jquery ajax http-headers

我有一个简单的ajax请求:

$.post('server.php',data, function (json) {console.log(json)},'json');

我已经设置好了,以便jQuery期望json按照上一个dataType设置的规定。

相关问题:dataType的另一个名称是responseType吗?见http://msdn.microsoft.com/en-us/library/windows/apps/hh871381.aspx

现在我真正的问题。 server.php有时返回json,有时返回html,有时返回xml,并在呈现响应时设置相应的标头。

然而,在呈现响应之前,服务器需要确定要提供的数据类型。我希望将响应基于它从客户端收到的dataType和/或responseType标头。如何在PHP中阅读此标题?

1 个答案:

答案 0 :(得分:0)

XMLHttpRequest.responseType属性,不是以任何形式发送到服务器的信息。因此,您无法使用此服务器的 php 代码来确定所请求的内容类型。

但是有一个名为ACCEPT的HTTP请求标头字段(请参阅mdn), 可以使用XMLHttpRequest.setRequestHeader()设置(再次参见mdn)。有了它,您可以通过$_SERVER['HTTP_ACCEPT']向您的php代码访问一些信息。{/ p>

在客户端,代替(或者除此之外)设置XMLHttpRequest.responseType,您可以执行此操作

// create XHR Object
var xhr =  new XMLHttpRequest();

// open request
xhr.open(<url to request>, "POST");

// set the responseType to json (which only provokes
// that the returned data is automatically interpreted
// by the browser as being json. saving you from manually
// doing a JSON.parse(xhr.responseText); 
xhr.responseType='json';

// set the request HTTP ACCEPT header to be the MIME of JSON 
// that is "application/json"
xhr.setRequestHeader("ACCEPT","application/json");

//[... setup the callbacks for handling the resonses or failures]

//send the request
xhr.send();

在服务器端,您可能会按照

的方式执行某些操作
if($_SERVER['HTTP_ACCEPT'] === 'application/json')
{
    header('Content-Type: application/json');
    echo '<json-string>';
    die(0);
}
else
{
    // do some stuff for other Request that do 
    // not want explicitly json.
}