【问题标题】:ajax returns empty string instead of json [python cgi]ajax 返回空字符串而不是 json [python cgi]
【发布时间】:2013-11-17 23:15:03
【问题描述】:

基本上,我有一个打印出有效 json 的 cgi 脚本,我已经检查过,并且我有一个类似的功能,它们的工作方式相同,但这个没有任何原因,我找不到它。

Javascript:

function updateChat(){ 
$.ajax({
            type: "get",
            url: "cgi-bin/main.py",
            data: {'ajax':'1', 'chat':'1'},
            datatype:"html",
            async: false,
            success: function(response) {
                alert(response); //Returns an empty string
            }, 
            error:function(xhr,err)
            {
                alert("Error connecting to server, please contact system administator.");
            }
        });

这是python打印出来的JSON:

[
"jon: Hi.",
"bob: Hello."
]

我使用 json.dumps 创建了它在以前的函数中工作的 JSON,这些函数具有几乎相同的 JSON 布局,只是内容不同。

还有一大堆服务器代码,我试图复制出相关部分。基本上我只是想过滤一个丑陋的聊天记录以供学习。我用正则表达式过滤它,然后从中创建一个 json。

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-

    print "Content-type: text/html\n\n"
    print 

    import cgi, sys, cgitb, datetime, re, time, random, json

    cgitb.enable()

    formdata = cgi.FieldStorage()


    def tail( f, window=20 ): 
        BUFSIZ = 1024
        f.seek(0, 2)
        bytes = f.tell()
        size = window
        block = -1
        data = []
        while size > 0 and bytes > 0:
            if (bytes - BUFSIZ > 0):
                # Seek back one whole BUFSIZ
                f.seek(block*BUFSIZ, 2)
                # read BUFFER
                data.append(f.read(BUFSIZ))
            else:
                # file too small, start from begining
                f.seek(0,0)
                # only read what was not read
                data.append(f.read(bytes))
            linesFound = data[-1].count('\n')
            size -= linesFound
            bytes -= BUFSIZ
            block -= 1
        return '\n'.join(''.join(data).splitlines()[-window:])


    def updateChatBox():
        try:
            f = open('test.txt', 'r')
            lines = tail(f, window = 20)
            chat_array = lines.split("\n")
            f.close()
        except:
            print "Failed to access data"
            sys.exit(4)

        i = 0
        while i < len(chat_array):
            #remove timer
            time = re.search("(\[).*(\])", chat_array[i])
            result_time = time.group()
            chat_array[i] = chat_array[i].replace(result_time, "")
            #Removes braces around user
            user = re.search("(\\().*?(_)", chat_array[i])
            result_user = user.group()
            chat_array[i] = chat_array[i].replace("(", "")
            chat_array[i] = chat_array[i].replace(")", "")
            #Removes underscore and message end marker
            message = re.search("(_).*?(\|)", chat_array[i])
            result_message = message.group()
            chat_array[i] = chat_array[i].replace("_", ":")
            chat_array[i] = chat_array[i].replace("|", "")
            data += chat_array[i] + "\n"
            i = i + 1
        data_array = data.split("\n")
        json_string = json.dumps(data_array)
        print json_string



    if formdata.has_key("ajax"):
        ajax = formdata["ajax"].value
        if ajax == "1": #ajax happens

            if formdata.has_key("chat"):
                    chat = formdata["chat"].value
                    if chat == 1:
                        updateChatBox()
                else:
                    print "ERROR"
                    elif formdata.has_key("get_all_stats"):
                            get_all_stats = formdata["get_all_stats"].value
                            if get_all_stats == "1":
                                getTopScores()
                    else:
                        print "ERROR"

这也是一个完美运行并且在同一个python文件中的函数

def getTopScores():
    try:
        f = open('test_stats.txt', 'r')
        stats = f.read()
        stats_list = stats.split("\n")
        f.close()
    except:
       print "Failed reading file"
       sys.exit(4)

    json_string = json.dumps(stats_list)
    print json_string

唯一的区别是使用tail函数和正则表达式,最终结果JSON实际上看起来相同。

【问题讨论】:

  • 你没有设置内容类型;您使用的 Python 服务器代码可能希望它知道如何解析数据。你也可以发布服务器代码吗?
  • 我添加了python,updateChatBox生成的JSON看起来和getTopScores创建的一模一样,都经过验证。

标签: javascript jquery python ajax json


【解决方案1】:

你确定updateChatBox 会被调用吗?请注意,您将 ajax 与字符串 "1" 进行比较,但将 chat 与整数 1 进行比较。我敢打赌其中一个不匹配(尤其是聊天那个)。如果不匹配,您的脚本将在没有返回值的情况下失败。

此外,虽然这不是根本原因,但您应该清理内容类型以确保正确性。您的 Javascript AJAX 调用被声明为期望 html 作为响应,并且您的 cgi 脚本也设置为返回 content-type:text/html。这些应分别更改为jsoncontent-type:application/json

【讨论】:

  • 天哪,就是这样.. 尝试找到像凌晨 2 点这样的错误不是一个好主意 :) 非常感谢!
猜你喜欢
  • 2017-08-17
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 2012-11-26
  • 2022-12-06
  • 1970-01-01
  • 2019-10-05
相关资源
最近更新 更多