[英]Return JSON object to View with Flask and Ajax
I am trying to return a python dictionary to the view with AJAX and reading from a JSON file, but so far I am only returning [object Object],[object Object]
... 我正在尝试使用AJAX将python字典返回到视图并从JSON文件读取,但是到目前为止,我只返回了[object Object],[object Object]
...
and if I inspect the network traffic, I can indeed see the correct data. 如果检查网络流量,我确实可以看到正确的数据。
So here is how my code looks like. 这就是我的代码的样子。 I have a class and a method which based on the selected ID (request argument method), will print specific data. 我有一个基于所选ID的类和方法(请求参数方法),将打印特定数据。 Its getting the data from a python discretionary. 它从python任意获取数据。 the problem is not here, have already just tested it. 问题不在这里,已经测试过了。 But just in case I will link it. 但以防万一我将其链接。
# method to create the directionary - just in case # #创建定向程序的方法-以防万一#
def getCourselist_byClass(self, classid):
"""
Getting the courselist by the class id, joining the two tables.
Will only get data if both of them exist in their main tables.
Returning as a list.
"""
connection = db.session.connection()
querylist = []
raw_sql = text("""
SELECT
course.course_id,
course.course_name
FROM
course
WHERE
EXISTS(
SELECT 1
FROM
class_course_identifier
WHERE
course.course_id = class_course_identifier.course_id
AND EXISTS(
SELECT 1
FROM
class
WHERE
class_course_identifier.class_id = class.class_id
AND class.class_id = :classid
)
)""")
query = connection.engine.execute(raw_sql, {'classid': classid})
for column in query:
dict = {
'course_id' : column['course_id'],
'course_name' : column['course_name']
}
querylist.append(dict)
return querylist
@main.route('/task/create_test')
def get_courselist():
#objects
course = CourseClass()
class_id = request.args.get('a', type=int)
#methods
results = course.getCourselist_byClass(class_id)
return jsonify(result=results)
and here is how the input field and where it should link the data looks like. 这是输入字段以及应该在哪里链接数据的样子。
<input type="text" size="5" name="a">
<span id="result">?</span>
<p><a href="javascript:void();" id="link">click me</a>
and then I am calling it like this 然后我这样称呼它
<script type=text/javascript>
$(function() {
$('a#link').bind('click', function() {
$.getJSON("{{ url_for('main.get_courselist') }}", {
a: $('input[name="a"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
but every time I enter a id number in the field, i am getting the correct data. 但是每次我在该字段中输入ID号时,我都会获得正确的数据。 but it is not formatted correctly. 但格式不正确。 It is instead printing it like [object Object] 相反,它像[object Object]一样打印
source, followed this guide as inspiration: flask ajax example 资料来源,并以此指南为灵感: flask ajax示例
The API description for flask.json.jsonify
indicates it's expecting keyword parameters. flask.json.jsonify
的API描述表明它需要关键字参数。 What you actually want to do seems to be serialize a list object containing dictionaries, have you tried flask.json.dumps
instead? 您实际上想要执行的操作似乎是对包含字典的列表对象进行序列化,您是否尝试过flask.json.dumps
呢? Assuming you've got the dumps
symbol imported, instead of your jsonify
call you can try: 假设您已经导入了dumps
符号,而不是您的jsonify
调用,您可以尝试:
return dumps(results)
The data return by your server is like: {result: [{course_id: 'xxx', course_name: 'xxx'}]}
, in which data.result
is a JS Array. 服务器返回的数据类似于: {result: [{course_id: 'xxx', course_name: 'xxx'}]}
,其中data.result
是一个JS数组。
when you set it to $("#result").text()
, JS convert a array to string, so the result is [object Object]
. 当您将其设置为$("#result").text()
,JS将数组转换为字符串,因此结果为[object Object]
。
You should iterate over the array to construct a string, then set the string in DOM, like: 您应该遍历数组以构造一个字符串,然后在DOM中设置该字符串,例如:
courseStr = data.result.map(function(course) {return course.course_id + '-' + course.course_name; }).join(',');
$("#result").text(courseStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.