简体   繁体   English

Python CGI以不同方式响应相同的jQuery / AJAX请求

[英]Python CGI responding in different ways to the same jQuery/AJAX request

I am implementing a system where to web pages (HTML + Javascript) communicate via CGI Python server side script. 我正在实现一个通过CGI Python服务器端脚本与网页(HTML + Javascript)进行通信的系统。 One of this pages makes a request: 以下页面之一发出请求:

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!");*/ });

  }

This request has either ?tweets=1 or ?tweets=0 , and the idea is that the server must return a different JSON object depending on that value. 该请求具有?tweets=1?tweets=0 ,并且想法是服务器必须根据该值返回不同的JSON对象。 On the sever I have: 在服务器上,我有:

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

This does not work. 这是行不通的。 The else clause (where option == 1) is executed fine, but the other option returns an unspecified object. 可以很好地执行else子句(其中option == 1),但另一个option返回未指定的对象。 I have tried in a number of ways (two different AJAX requests, etc) but it doesn't work. 我已经尝试了多种方法(两个不同的AJAX请求等),但是它不起作用。 It does not like multiple requests or multiple returns. 它不喜欢多个请求或多个返回。 Any ideas? 有任何想法吗?

The problem was very simple indeed. 这个问题确实非常简单。 In the Python CGI script, when I do if tweets == 1: ... else: ... it always goes to the else clause, because I am comparing a "tweets" which is a string that comes from FieldStorage and the number 1. It never evaluates to true, hence it always returns the same answer. 在Python CGI脚本中,当if tweets == 1: ... else: ...总是转到else子句,因为我正在比较“ tweets”(这是来自FieldStorage的字符串)和数字1.它永远不会求真,因此总是返回相同的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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