我有以下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结构,但不知道如何过滤掉所需的特定字段。
答案 0 :(得分:2)
当您不使用内联函数时,代码会变得更清晰。让我们为成功分配一个函数句柄:
jQuery.ajax({
...
dataType: "json",
success: myJSONsuccess;
...
});
所以必须有一个名为&#34; myJSONsuccess&#34;:
的函数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
};
答案 1 :(得分:0)
在将其添加到标记之前,您需要进行更多处理。记住这些不是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值以查看它是否重复。