【问题标题】:Python CGI responding in different ways to the same jQuery/AJAX requestPython CGI 以不同的方式响应相同的 jQuery/AJAX 请求
【发布时间】:2013-03-01 23:06:13
【问题描述】:

我正在实现一个系统,其中网页(HTML + Javascript)通过 CGI Python 服务器端脚本进行通信。此页面之一发出请求:

function doQuery(tweets) {

    $.getJSON("http://linuxproj.ecs.soton.ac.uk/~onme1g10/watchitlater/cgi-bin/engine.cgi?loading="+ uid +"&tweets="+ tweets, function(data) {

    }
    )
    .success(function(data) {
      //alert("complete: " + data['test']);
      if (tweets == 1) {
        //console.log('tweets is one')
        tweetsData = data;
        length = Object.keys(tweetsData["tweets"]).length;
        intervalVar = window.setInterval(showTweets, 1000);
        intervalVar2 = window.setInterval(queryState, 1500);
        //console.log("set intervals");
      }
      else {
        console.log('HERE: ' + data["correct"])
        queryData = data;
        // Function to update state variables
      }
    })
    .error(function(xhr, textStatus, error) {
      //alert("error:" + textStatus);
      console.log(xhr);
      console.log(textStatus);
      console.log(error);
    })
    .complete(function() {/*alert("complete!");*/ });

  }

此请求具有?tweets=1?tweets=0,其想法是服务器必须根据该值返回不同的 JSON 对象。在我拥有的服务器上:

if fs.has_key('state'):
    createStateFile()
elif fs.has_key('loading'):
    # Return JSON objects
    print "Content-type: application/json"
    print
    option = fs['tweets'].value
    if option == 0:
        response = {'correct':'1'}
        print(json.JSONEncoder().encode(response))
    else:
        response = harvestTweets()
        print(json.JSONEncoder().encode(response))

else:
    # Return main page
    print "Content-type: text/html"
    print
    main()

这不起作用。 else 子句(其中 option == 1)执行得很好,但另一个选项返回一个未指定的对象。我尝试了多种方式(两个不同的 AJAX 请求等),但它不起作用。它不喜欢多次请求或多次返回。有什么想法吗?

【问题讨论】:

  • 那么harvestTweets()返回什么?
  • 返回:tweets = json.load(myFile) 其中 myFile 是一个 jason 对象文件。
  • 那么,1. 为什么不直接读取并返回该文件,而不是解码然后重新编码 JSON,以及 2. 为什么使用 json.JSONEncoder().encode 而不仅仅是 json.dumps
  • 你是对的,我没有意识到这一点。然而,你认为我的问题在那里吗?系统的那部分工作正常,我可以毫无问题地获得推文,问题是当我尝试获得其他东西时,在这种情况下是一个简单的 {"correct":"1"} Json 对象。

标签: javascript python json jquery cgi


【解决方案1】:

问题确实很简单。在 Python CGI 脚本中,当我执行 if tweets == 1: ... else: ... 时,它总是转到 else 子句,因为我正在比较一个来自 FieldStorage 的字符串和数字 1 的“tweets”。它永远不会评估为 true,因此它总是返回相同的答案。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2018-09-24
    • 2014-09-10
    • 2020-07-07
    相关资源
    最近更新 更多