【问题标题】:jsonify() and jsonify([]) returning different results in jQueryjsonify() 和 jsonify([]) 在 jQuery 中返回不同的结果
【发布时间】:2018-01-13 10:47:30
【问题描述】:

编辑

typeahead 假定从您的 source: 数据集检索到的结果是数组(并按原样解析它们)

传入单个 JSONified dict{} 会引发 Typeahead 错误。

(see below)


我正在尝试在 Typeaheadtemplates 选项 (js) 中解析单个字典 (python):

想象一下 dict 看起来像 {"id": 1, "name": "us", "place": "idaho"}

  // trying to parse a dict obj here
  templates: 
       {
       suggestion: Handlebars.compile("<div>+{{ key }}+</div>") 
       }

1.

dict 作为flask.jsonify([dict]) 传递——{{ key }} 有效。

dict 以flask.jsonify(dict) 传递——{{ this.key }} 有效,{{ key }} 无效,jQuery 如何访问此 dict?

2.

脚本是这样运行的吗?

(when a query ("#q") is typed)

  code

 (.js)                                    (.js)                                                 asyncResults(data) passed to            (.js)
    typeahead {source: func1(*kwargs)} ----> func1(query, syncResults, asyncResults): ------------------------------------------------> typeahead {suggestion: Handlebars.compile()}
              ^calls function1                $.getJSON("/url", params, func2(data,textStatus,jqXHR))   (.py)                                     ^uses asyncResults(data) as associated Suggestion object
                                                        ^sends GET request to "/url" -----------------> function at ("/url")                         (i.e suggestion.data = whatever was returned from asyncResults()?)
                                                                ^calls func2 on success <-------------  ^return jsonify(result) as data
                                                                        ^return asyncResults(data)       
                                                                                 [AsyncFunction object]   

代码:

script.js

function configure()
{
    $("#q").typeahead(

        // options
        {   highlight: false,
            minLength: 1
        },

        // *dataset
        {   display: function(suggestion) {return null;},
            limit: 10,
            source: search,
            templates: {
                suggestion: Handlebars.compile("<div>" + "{{ id }}" + "</div>");}
        }
     );
}

function search(query, syncResults, asyncResults)
{
    let params = { q: query };

    $.getJSON("/search",
                 params,
                 function(data, textStatus, jqXHR){
                         asyncResults(data);
                 }
              );
}

app.py

from flask import Flask, jsonify, json, render_template, request
from sqlalchemy import *

@app.route("/search")
def search():
    if request.method == "GET":
        query = request.args.get("q")
        stmt = table.select().where(table.c.place_name.startswith(query))
        _result = dbsession.query(stmt).scalar()

        result = {}
        for _row in _result:
            for k,i in zip( _row.keys(), range(len(_row.keys())) ):
                result.setdefault(k, _row[i])

    return jsonify(result) 

故障排除

引用的变量:

// from search() in "app.py"
result = {'id': 2, 'name': 'user', 'place': 'idaho'} 
<type 'dict'>

// from $("q").typeahead() from configure() in "script.js"
suggestion = Handlebars.compile("<div>" + "{{ id }}" + "</div>")

// from $.getJSON() from search() in "script.js"
data = [object Object]
(typeof data = object)

search()app.py 中:

if jsonify(result)   // typeahead shows nothing (i.e suggestion not showing {{ id }} )
if jsonify([result]) // typeahead works (i.e suggestion shows {{ id }} )

search()script.js 中:

 if jsonify(result)   // alert(data["key"]) shows key value
 if jsonify([result]) // alert(data[0]["key"]) shows key value

 alert(data)        // returns "[object Object]"
 alert(typeof data) // returns "object"

参考文档:

【问题讨论】:

  • 您的很多代码都包含散布在代码中的注释,或者在语法上无效的代码。此外,您的代码在这里由两部分组成:一部分通过 AJAX 下载内容,另一部分通过把手呈现内容。你的问题是这两者中的哪一个?此外,虽然包含大量代码通常很棒,但我对代码的哪一部分做了什么有点困惑。是否可以将问题提炼到一个失败的程序部分?行得通的代码根本不用提。
  • 感谢您的反馈,老实说,我不确定问题出在哪里,所以一切哈哈。这需要一些时间来清理,希望到那时我能找到答案!

标签: jquery python flask handlebars.js typeahead


【解决方案1】:

哇哦。解决了!

typeahead 解析您的回调结果(即关联的建议对象)as an array.

在回调之前将 dict 转换为数组/列表使一切按预期工作。

要么

if (!data.length){
     data = [data];}
asyncResults(data);

jsonify([dict])

dataset.js from typeahead source

function async(suggestions) {
suggestions = suggestions || [];

if (!canceled && rendered < that.limit) {
          that.cancel = $.noop;

          // dict.length is 'undefined'
          rendered += suggestions.length; 

          // and this would just raise an error (i.e. "suggestions.slice(..) is undefined")
          that._append(query, suggestions.slice(0, that.limit - rendered)); 

          that.async && that.trigger('asyncReceived', query);
}

感谢jFensch 指出这一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2011-10-29
    • 2014-11-26
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多