gpt4 book ai didi

javascript - PHP判断客户端请求的dataType或responseType

转载 作者:行者123 更新时间:2023-11-28 08:31:11 25 4
gpt4 key购买 nike

我有一个简单的ajax请求:

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

我已经将其设置为 jQuery 需要最后一个 dataType 设置指定的 json。

相关问题:dataTyperesponseType 的另一个名称吗?请参阅http://msdn.microsoft.com/en-us/library/windows/apps/hh871381.aspx

现在是我真正的问题。 server.php 有时返回 json,有时返回 html,有时返回 xml,并且在渲染响应时会设置适当的 header 。

但是,在呈现响应之前,服务器需要确定要提供的数据类型。我希望响应基于从客户端接收到的 dataType 和/或 responseType header 。如何在 PHP 中读取此 header ?

最佳答案

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

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

在客户端,您可以执行此操作来代替(或补充)设置 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.
}

关于javascript - PHP判断客户端请求的dataType或responseType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21854779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com