HTTP Content-Type Header and JSON

2019-01-10 10:04发布

问题:

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);
}

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

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

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?

回答1:

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.

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.

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.



回答2:

Content-Type: application/json is just content header, the content header is just information about type of returned data, ex::JSON,image(png,jpg,etc..),html. Keep in mind, that JSON in javascript is an array or object. if you want to see all the data, use console.log instead of alert

alert(response.text);//will alert "[object Object]" string
console.log(response.text);//will logging all data object

if you want to alert original JSON as string, than add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
//alert(response.text) will alert {"text":"omrele"}

Do not use double quotes, it will confuse javascript, because JSON uses double quote on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

//it will return wrong javascript code: 
<script>var returndata="{"text":"omrele"}";</script>


回答3:

The below code help me to return a json object for js in the FronEnd

My template code template_file.json

{
    "name": "{{name}}"
}

python backed code

def download_json(request):
    print("Downloading json")
    #response render a template as json object
    return HttpResponse(render_to_response("template_file.json",dict(name="Alex Vera")),content_type="application/json")    

url.py

url(r'^download_as_json/$',views.download_json,name='download_json-url')

Jquery code for FrontEnd

  $.ajax({
        url:'{% url 'download_json-url' %}'        
    }).done(function(data){
        console.log('json ',data);
        console.log('Name',data.name);
        alert('hello '+data.name);
    });