[英]Get JSON response at javascript
我正在使用JSON对象回答对我的Django服务器的某个请求:
return HttpResponse(json.dumps(geojson), mimetype="application/json")
但是我不知道如何在HTML / javascript中获得它。 我经历了很多类似的问题和教程,但是他们都开始定义一个带有JSON示例的字符串变量来使用它。 但是我还无法找到如何获取服务器正在回答我的JSON。
有帮助或教程链接吗?
编辑:我尝试按照建议使用jQuery.ajax,但该函数从未执行过:
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
});
我还有一个表单的另一个js文件,可以正常工作。 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>
因此,当收到来自服务器的json的POST请求时,应执行jQuery.ajax方法,并且地图应显示一些数据(准确地在其上绘制多边形)。 如FireBug所述,该POST可以使OK正常(快照未显示整个json对象,该对象很大):
您是否将对象序列化为json格式?
$.ajax({
url: //your_url,
type: "POST",
success: function (data) {
// write your parsing code..
}
},
error: function (err) {
}
});
来自w3schools.com的exp json
{
"people": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
解析exp(在jquery ajax成功函数中):
$.each(data.people, function (i, person) {
console.log(person.firstName + " " + person.lastName)
});
您可以在浏览器端使用jQuery进行请求。
$.ajax({
url: "example.com/data",
dataType: "json"
}).done(function (data) {
// data is the javascript object from the json response
});
编辑:链接到错误的jQuery调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.