简体   繁体   English

通过JavaScript获取JSON响应

[英]Get JSON response at javascript

I'm answering a certain request to my Django server with a JSON object: 我正在使用JSON对象回答对我的Django服务器的某个请求:

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

But I don't know how to get it at the HTML/javascript. 但是我不知道如何在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. 我经历了很多类似的问题和教程,但是他们都开始定义一个带有JSON示例的字符串变量来使用它。 But I haven't been able to find how to get the JSON the server is answering me. 但是我还无法找到如何获取服务器正在回答我的JSON。

Any help or tutorial link? 有帮助或教程链接吗?

EDIT: I tried using jQuery.ajax as suggested, but the function is never being executed: 编辑:我尝试按照建议使用jQuery.ajax,但该函数从未执行过:

Content of map-config.js: 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. 我还有一个表单的另一个js文件,可以正常工作。 And the HTML file is this one: HTML文件就是这样的:

<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). 因此,当收到来自服务器的json的POST请求时,应执行jQuery.ajax方法,并且地图应显示一些数据(准确地在其上绘制多边形)。 That POST is arraiving OK as stated at FireBug (the snapshot is not showing the whole json object, which is big): 如FireBug所述,该POST可以使OK正常(快照未显示整个json对象,该对象很大):

FireBug上的JSON响应快照

Did you serialize your object to json format ? 您是否将对象序列化为json格式?

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

        }
    });

exp json from w3schools.com 来自w3schools.com的exp json

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

parsing exp (in jquery ajax success function ): 解析exp(在jquery ajax成功函数中):

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

You could use jQuery for the request on the browser side. 您可以在浏览器端使用jQuery进行请求。

$.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. 编辑:链接到错误的jQuery调用。

See details 阅读详情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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