$ .parseJSON返回正确的项目以及无限的未定义响应

时间:2018-01-17 01:39:18

标签: javascript python ajax flask

我目前正在开发一个烧瓶应用程序,用于从足球联赛中检索球队。 teams_list方法从ajax请求返回以下响应。我得到了正确的输出,但它引导我进入一个无限循环,真正减慢整个Web应用程序。

我是如何得到答复的:

teams = []
@app.route('/get_team_list', methods=['POST'])
    def team_list():
        league = request.form['team_name']
        id = get_league_id(league)
        get_teams(id)

        json_str = json.dumps({'status':'OK','id': id, 'league': league, 'teams': teams})
        json_obj = json.loads(json_str)

        temp = json_obj['teams'] #a subarray
        team_str = json.dumps(temp)
        print("STR:  ",team_str)
        print("JSON: ", str(temp))

        clear_team_array(teams)
        return team_str

响应:

["Juventus Turin", "Cagliari Calcio", "Hellas Verona FC", "SSC Napoli", "Atalanta BC", "AS Roma", "Udinese Calcio", "AC Chievo Verona", "US Sassuolo Calcio", "Genoa CFC", "UC Sampdoria", "Benevento Calcio", "SS Lazio", "SPAL Ferrara", "FC Internazionale Milano", "ACF Fiorentina", "Bologna FC", "Torino FC", "FC Crotone", "AC Milan"]

Ajax电话:

$('#test').click(function() {
   $.ajax({
       url: '/get_team_list',
       data: $('form').serialize(),
       type: 'POST',
       success: function(response) {
           var json = $.parseJSON(response);
                for (var i = 0; json.length - 1; i++) {
                    console.log("RESPONSE: " + json[i]);
                }
       },
       error: function(error) {
           console.log("ERROR: "+ error)
       }
   });
});

工作正常,但我正在解决的问题是,当我通过for loop检索团队时,它会给我以下输出:

RESPONSE: Juventus Turin
RESPONSE: SSC Napoli
RESPONSE: Atalanta BC
RESPONSE: AC Milan
RESPONSE: ...
(140231)REPONSE: undefined

1 个答案:

答案 0 :(得分:0)

循环条件是json.length - 1,它永远不会改变,因此循环会永远持续下去。

应该是

for (var i = 0; i < json.length; i++) {