我有以下ajax函数:
jQuery.ajax({
method: "PUT",
dataType: 'json',
callback: null,
url: urlLocation,
data: saveImage,
success: function(response){
$(".response").html(JSON.stringify(response, null, ' ').replace(/\n/g, '<br>'));
$(".response").css('font-family', 'Knowledge');
},
error: function (data) {
$(".share-link").html("<div class='alert alert-danger'><p>Couldn't send photo: <b>"+ imageid.value + "</b></p></div>");
}
});它返回一个响应
{
"status": {
"code": 200,
"description": "OK"
},
"entity": {
"entityType": "EntityMap",
"entryKeyType": "Orientation",
"entryValueType": "ImageResource",
"entries": {
"SQUARE": {
"uri": "http://www.url.com/image-file",
"orientation": "SQUARE",
"entityType": "ImageResource"
},
"PORTRAIT": {
"uri": "http://www.url.com/image-file",
"orientation": "PORTRAIT",
"entityType": "ImageResource"
},
"LANDSCAPE": {
"uri": "http://www.url.com/image-file",
"orientation": "LANDSCAPE",
"entityType": "ImageResource"
}
}
}
}我需要解析出值SQUARE、PORTRAIT和LANDSCAPE及其相关的uri和orientation值。然后,我需要能够将uri封装在一个img标记中。到目前为止,我可以只提出JSON结构,但不确定如何过滤出所需的特定字段。
发布于 2015-04-20 20:37:24
在将其添加到标记之前,您需要进行更多的处理。记住,这些不是HTML,它们是JSON,当您对响应调用parseJSON时,您将拥有javascript对象,而不是HTML元素。你想要的更像是
var obj = $.parseJSON(response.responseText);
for (var property in obj.entity.entries) {
if (obj.entity.entries.hasOwnProperty(property)) {
$(".response").append($("<img alt='test' src='" + obj.entity.entries[property].uri + "'/>"));
}
}以及您可能需要添加到响应中的任何其他内容。
您可以在添加的每个图像中添加一个id,然后在将其附加到响应div之前检查它是否已经存在,或者您可以查看src值以查看它是否为副本。
发布于 2015-04-20 19:58:14
当您不使用内联函数时,代码变得更加清晰。让我们为成功分配一个函数句柄:
jQuery.ajax({
...
dataType: "json",
success: myJSONsuccess;
...
});因此,必须有一个名为“myJSONsuccess”的函数:
var myJSONsuccess = function (JSONobj, StatusString, jqXHR) {
//you probably will not need StatusString and jqXHR, so ignore them
//There is no need to parse JSONobj. It is already parsed because of
//dataType: "json"
//in your ajax-command
//This is SQUARE:
var squ = JSONobj.entity.entries.SQUARE;
//This is one of its properties:
var orient = JSONobj.entity.entries.SQUARE.orientation;
//alternatively you can write:
var orient = squ.orientation;
//this is exactly the same
};https://stackoverflow.com/questions/29756900
复制相似问题