简体   繁体   中英

How to format a HTTP response to a HTTP request coming from a getJSON() jQuery call

Here's the thing:

I'm creating a completely custom server for my thesis. At the client side, I want to be able to request a database call which the server processes. It then gives a response in HTTP, providing the query result in JSON.

The way I do the call at the moment: using JQuery's 'getJSON()' method.

dummy example:

<script type="text/javascript">
        $(document).ready(function(){
                $.getJSON('./db/q="select * from *"', function(result){
                    process(result);
                });
        });
</script>

Running a web page with this script in the browser yields the following HTTP Header at the server side:

request: GET /db/q="select * from *"
Host: 127.0.0.1:9000
Connection: keep-alive
Accept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Referer: http://127.0.0.1:9000/web/widgets/gauge.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4,id;q=0.2

My question: how would a HTTP 1.1 response from the server to the browser look like, in order to get the JSON payload from the response in the 'result' parameter in the javascript on the browser?

  1. To get JSON data via AJAX with jQuery you don't need to use getJSON. Any $.get , $.post , $.ajax parse automatically JSON if they see it in the response.

  2. There's no specific format for the body. As long as it's valid JSON, jQuery will put the root of the JSON object into result . For example, if your response is {foo: 'bar'} , your result object will have the result.foo propety set to "bar" .

  3. In your response, to make jQuery automatically treat the content as JSON, you need to specify the header Content-Type: application/json . All the other headers are irrelevant.

  4. It may be a better idea to move the query from a GET parameter to a POST one, so you don't have to url-encode it on the query string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM