jsonify()和jsonify([])在jQuery中返回不同的结果

时间:2018-01-13 10:47:31

标签: jquery python flask handlebars.js typeahead

修改

typeahead假设从source:数据集中检索到的结果是数组(并按原样对其进行解析)

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

(see below)

我正在尝试在 Typeahead templates选项(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如何访问此词典?

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)
app.py 中的

search()

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

中的

search()

 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"

提及的文档:

1 个答案:

答案 0 :(得分:0)

哦,哇。解决!

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指出