简体   繁体   中英

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] ...

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. Its getting the data from a python discretionary. 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

my jsonify route method

@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)

HTML

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. but it is not formatted correctly. It is instead printing it like [object Object]

source, followed this guide as inspiration: flask ajax example

The API description for flask.json.jsonify indicates it's expecting keyword parameters. What you actually want to do seems to be serialize a list object containing dictionaries, have you tried flask.json.dumps instead? Assuming you've got the dumps symbol imported, instead of your jsonify call you can try:

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.

when you set it to $("#result").text() , JS convert a array to string, so the result is [object Object] .

You should iterate over the array to construct a string, then set the string in DOM, like:

courseStr = data.result.map(function(course) {return course.course_id + '-' +   course.course_name; }).join(',');
$("#result").text(courseStr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM