HTTP Content-Type标头和JSON [英] HTTP Content-Type Header and JSON

查看:181
本文介绍了HTTP Content-Type标头和JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我一直在努力避免使用大多数HTTP协议的属性,或者为了害怕未知,你可以随意调用它们。但是我告诉自己,我今天要面对恐惧并开始有目的地使用标题。我在这里尝试实现的是将 json 数据发送到浏览器并立即使用它。例如,如果我在就绪状态4上有一个ajax处理函数,看起来像这样

Ok so I have always been trying to avoid using most of the HTTP protocol's properties or how ever you may please to call them for the sake of fear of the unknown. However I said to myself that I'm going to face fear today and start using headers purposefully. What I have been trying to achieve here is send json data to the browser and use it right away. For example if I have an ajax handler function on ready state 4 which looks like so

function ajaxHandler(response){
    alert(response.text);
}

我在php中设置了内容类型标题

and I have set the content-type header in my php

header('Content-Type: application/json');
echo json_encode(array('text' => 'omrele'));

我的问题是:为什么我不能直接从处理程序函数访问属性,当浏览器明确告知传入的数据是 application / json

My question is: Why can't I directly access the property from the handler function, when the browser is clearly told that the incoming data is application/json?

推荐答案

Content-Type 标题仅用作应用程序的信息。浏览器并不关心它是什么。浏览器只返回AJAX调用中的数据。如果你想把它解析为JSON,你需要自己做。

The Content-Type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

标题就在那里,所以你的应用程序可以检测返回了什么数据以及它应该如何处理它。您需要查看标题,如果它是 application / json ,则将其解析为JSON。

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

这是实际上jQuery是如何工作的。如果您不告诉它如何处理结果,它会使用 Content-Type 来检测如何处理它。

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.

这篇关于HTTP Content-Type标头和JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆