简体   繁体   中英

Get JSON response at javascript

I'm answering a certain request to my Django server with a JSON object:

return HttpResponse(json.dumps(geojson), mimetype="application/json")

But I don't know how to get it at the HTML/javascript. I have gone through lots of similar questions and tutorials, but they all start defining an string variable with an example of JSON to use it. But I haven't been able to find how to get the JSON the server is answering me.

Any help or tutorial link?

EDIT: I tried using jQuery.ajax as suggested, but the function is never being executed:

Content of map-config.js:

var jsondata;
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;

function init(){
    map = new OpenLayers.Map( 'map' );
    layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", 
            "http://vmap0.tiles.osgeo.org/wms/vmap0",
            {layers: 'basic'} );
    map.addLayer(layer);
    map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);

    var geojson_format = new OpenLayers.Format.GeoJSON();
    var vector_layer = new OpenLayers.Layer.Vector(); 
    map.addLayer(vector_layer);
    vector_layer.addFeatures(geojson_format.read(jsondata)); // Feeding with the json directly
}

$.ajax({
  url: "localhost:8000/form/",
  type: "POST",
  dataType: "json"
}).done(function (data) {
  $("#dialog").dialog('Hello POST!');
  console.log(data);
  jsondata = data; // Saving JSON at a variable so it can be used with the map
});

I also have another js file for a form, which works properly. And the HTML file is this one:

<html>
<head>  
    <script src="{{STATIC_URL}}js/jquery-1.9.1.js"></script>
    <script src="{{STATIC_URL}}js/jquery-ui-1.10.3.custom.js"></script>
    <script src="{{STATIC_URL}}js/OpenLayers.js"></script>
    <script src="{{STATIC_URL}}js/form.js"></script>
    <script src="{{STATIC_URL}}js/map-config.js"></script>
    <link rel="stylesheet" href="{{STATIC_URL}}css/jquery-ui-1.10.3.custom.css">
    <link rel="stylesheet" href="{{STATIC_URL}}css/style.css" type="text/css">
</head>

<body onload="init()">
    <div id="form" class="form-style">
        <p>Start Date: <input type="text" id="id_startDate"></p>
        <p>
            <label for="amount">Interval:</label>
            <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
        </p>
        <p> <div id="id_interval"></div> </p>

        <p>
          <button id="id_okButton">OK</button>
        </p>
        </p>
    </div>

    <div id="map" class="smallmap">
</body>

So, when the POST request is received with the json coming from server, the jQuery.ajax method should execute, and the map should show some data (draw polygons over it to be exact). That POST is arraiving OK as stated at FireBug (the snapshot is not showing the whole json object, which is big):

FireBug上的JSON响应快照

Did you serialize your object to json format ?

    $.ajax({
        url: //your_url,
        type: "POST",
        success: function (data) {
              // write your parsing code..
            }
        },
        error: function (err) {

        }
    });

exp json from w3schools.com

{
"people": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

parsing exp (in jquery ajax success function ):

$.each(data.people, function (i, person) {
  console.log(person.firstName + " " + person.lastName)
});

You could use jQuery for the request on the browser side.

$.ajax({
  url: "example.com/data",
  dataType: "json"
}).done(function (data) {
  // data is the javascript object from the json response
});

Edit: Linked to the wrong jQuery call.

See details

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