ajax 处理json数据

{% block add_js %}
    <!--add_js_666-->
    <script>
        $.ajax({
            type: "get",
            dateType: "json",
            url: "/api/v1/post/recent",
            //async: false,
            complete: function () {
                $("#load").hide();
            },
            success: function (msg) {
                $.each(msg,function (i,n) {
                    $("#writing ul").append(
                       '<li class="post-item"><div class="meta">' +
                        '<time datetime="'+ n[0].date +'" itemprop="datePublished">'+ n[0].date.substr(5,12) +'</time></div>'
                        +  '<span><a class="" href="/post/'+ n[1] +'">' + n[0].title + '</a></span></li>'
                    );
                })
            },
            error: function () {
                alert("ERROR");
            }
        });
    </script>
{% endblock %}
# json
{
  "2016-09-09-xxx": [
    {
      "author": "66666", 
      "date": "Mon, 11 Sep 2017 00:00:00 GMT", 
      "desc": "test page", 
      "tags": "test1 blog1", 
      "title": "test1"
    }, 
    "2016-09-09-xxx"
  ], 
  "2017-09-05-xxx": [
    {
      "author": "6666", 
      "date": "Sun, 10 Sep 2017 00:00:00 GMT", 
      "desc": "test page", 
      "tags": "test22 blog", 
      "title": "test3"
    }, 
    "2017-09-05-xxx"
  ]
}

后端处理简单调整测试了一下

@api.route('/api/v1/post/<name>')
def api_post(name):
    if name == 'all':
        return jsonify({key.path: {key.meta, key.path} for key in post.get_posts_list()})
    elif name == 'recent':
        return jsonify({key.path: [key.meta, key.path] for key in post.recent_post()})
    else:
        return redirect(url_for('api.api_index'))
阅读 4k
3 个回答

你写的有点混乱,而且貌似基本不懂 js 还有 jq

这是jq的遍历操作

jQuery.each( array, callback )
jQuery.each( object, callback )

ajax success 的回调函数中 msg 是 json 数据,所以需要先转化成 object

 // 下面就是你想获取的2017-09-05-xxx内容
 success: function (res) {
    var msg = JSON.parse(res)
    var date = msg['2017-09-05-xxx'].date
    console.log(date)
 },
 // 如果想获取所有内容,遍历,然后插入
 success: function (res) {
        var msg = JSON.parse(res)
        $.each(msg,function (key, val) {
            $("#writing ul").append(
                '<li class="post-item"><div class="meta">' +
                '<time datetime="'+ val.date +'" itemprop="datePublished">'
                + n.date.substr(5,12) +'</time></div>'
                +  '<span><a class="" href="#'+  val.date // 这里就是每个的 date
                + '">' + n.title + '</a></span></li>'
            );
        })
    },

知道序号的话输出整个object
console(msg[1])
输出object的attribute
console(msg[1].author)...
循环输出接收的object
.success(function(msg){

for(var i=0;i<msg.length;i++){
    console.log(msg[i])
}

})

不知道题主的问题能解决吗?

json数据为什么不是数组的形式,对象的属性是没有顺序的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题