dongpo1203
2017-10-05 11:40
浏览 46

AJAX - 在JQUERY中返回的Parse JSON对象

I stucked a little bit in here>

My php script returns this JSON (in variable response) (encoded array with json_encode) :

{"1":{"id":"pvv001","tooltip":"tip1","link":"http:\/\/domain\/file1.html"},"2":{"id":"pvv002","tooltip":"tip2","link":"http:\/\/domain\/file2.html"}}

I hope this is valid JSON object ...

Then here is JavaScript function which should get this string and process it - load to ELEMENT "id" a content of "link".

function jLinks(idchapter)
{
    var url = 'ajax_loadlinks.php';
    var data = {
        idchapter : idchapter
    };
    $.post(url,data, function(response)
    {
        //$('#coursecontent').html(response);

        var obj = JSON.parse(response);
        for (var i=0; i<obj.length; i+1)
        {
            $('#'+obj[i].id).html('<a href="'+obj[i].link+'">link</a>');
        }

    });
}

It is not throwing any error in browser or console, but elements are not updated at all.

I quess my parsing and accessing data is wrong somehow, but I have no idea how to debug.

图片转代码服务由CSDN问答提供 功能建议

我在这里加了一点&gt;

我的php脚本返回此 JSON(在变量响应中)(带有json_encode的编码数组):

  {“1”:{“id”:“pvv001”,“tooltip”:“tip1”,“ 链接 “:” HTTP:\ / \ /域\ /file1.html “},” 2 “:{” ID “:” pvv002" , “提示”: “提示2”, “链接”:“HTTP:\ / \  /domain\/file2.html"}}
nn

我希望这是有效的JSON对象......

然后在这里 是JavaScript函数,应该获取此字符串并处理它 - 加载到ELEMENT“id”内容“link”。

  function jLinks(idchapter)
 {
 var  url ='ajax_loadlinks.php'; 
 var data = {
 idchapter:idchapter 
}; 
 $ .post(url,data,function(response)
 {
 // $('#coursecontent'  ).html(响应); 
 
 var obj = JSON.parse(response); 
 for(var i = 0; i&lt; obj.length; i + 1)
 {
 $('#'  + obj [i] .id).html('&lt; a href =“'+ obj [i] .link +'”&gt; link&lt; / a&gt;'); 
} 
 
}); 
  } 
   
 
 

它没有在浏览器或控制台中抛出任何错误,但元素根本没有更新。

我解析我的解析和访问数据是错误的, 但我不知道如何调试。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongsi8812 2017-10-05 11:53
    已采纳

    As your string is an object not array, so you need $.each method to loop over each key of object.

    var obj ={
      "1": {
        "id": "pvv001",
        "tooltip": "tip1",
        "link": "http:\/\/domain\/file1.html"
      },
      "2": {
        "id": "pvv002",
        "tooltip": "tip2",
        "link": "http:\/\/domain\/file2.html"
      }
    };
    
    $.each(obj,function(i,v){
        $('#'+v.id).html('<a href="'+v.link+'">link</a>');
    });
    

    Fiddle

    打赏 评论
  • dongweishi2028 2017-10-05 11:52

    please try this

     for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
              console.log(obj[prop].id);
              $('#'+obj[prop].id).html('<a href="'+obj[prop].link+'">link</a>');
        }
    }
    
    打赏 评论

相关推荐 更多相似问题