首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在jQuery中显示JSON响应中的特定值

在jQuery中显示JSON响应中的特定值
EN

Stack Overflow用户
提问于 2015-04-20 19:41:13
回答 2查看 1.2K关注 0票数 0

我有以下ajax函数:

代码语言:javascript
复制
jQuery.ajax({
    method: "PUT",
    dataType: 'json',
    callback: null,
    url: urlLocation,
    data: saveImage,
    success: function(response){
        $(".response").html(JSON.stringify(response, null, '&nbsp').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>");
    }
});

它返回一个响应

代码语言:javascript
复制
{
 "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"
   }
  }
 }
}

我需要解析出值SQUAREPORTRAITLANDSCAPE及其相关的uriorientation值。然后,我需要能够将uri封装在一个img标记中。到目前为止,我可以只提出JSON结构,但不确定如何过滤出所需的特定字段。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-20 20:37:24

在将其添加到标记之前,您需要进行更多的处理。记住,这些不是HTML,它们是JSON,当您对响应调用parseJSON时,您将拥有javascript对象,而不是HTML元素。你想要的更像是

代码语言:javascript
复制
 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值以查看它是否为副本。

票数 0
EN

Stack Overflow用户

发布于 2015-04-20 19:58:14

当您不使用内联函数时,代码变得更加清晰。让我们为成功分配一个函数句柄:

代码语言:javascript
复制
jQuery.ajax({
    ...
    dataType: "json",
    success: myJSONsuccess;
    ...
});

因此,必须有一个名为“myJSONsuccess”的函数:

代码语言:javascript
复制
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
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29756900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档