Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

javascript - HTTP Content-Type标头和JSON(HTTP Content-Type Header and JSON)

I have always been trying to avoid using most of the HTTP protocol's properties for the sake of fear of the unknown.(为了害怕未知,我一直试图避免使用大多数HTTP协议的属性。)

However, I said to myself that I'm going to face fear today and start using headers purposefully.(但是,我告诉自己今天我将面临恐惧并开始有目的地使用标题。)

I have been trying to send json data to the browser and use it right away.(我一直在尝试将json数据发送到浏览器并立即使用它。) For example, if I have an Ajax handler function on ready state 4 which looks like so:(例如,如果我在就绪状态4上有一个Ajax处理函数,它看起来像这样:)
function ajaxHandler(response){
    alert(response.text);
}

And I have set the content-type header in my PHP code:(我在PHP代码中设置了content-type标头:)

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

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 ?(为什么我不能直接从处理函数访问属性,当浏览器被明确告知传入的数据是application/json ?)

  ask by php_nub_qq translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Content-Type header is just used as info for your application.(Content-Type标头仅用作应用程序的信息。)

The browser doesn't care what it is.(浏览器并不关心它是什么。) The browser just returns you the data from the AJAX call.(浏览器只返回AJAX调用中的数据。) If you want to parse it as JSON, you need to do that on your own.(如果要将其解析为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.(您需要查看标头,如果是application/json则将其解析为JSON。)

This is actually how jQuery works.(这实际上就是jQuery的工作原理。)

If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.(如果您不告诉它如何处理结果,它会使用Content-Type来检测如何处理它。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...