简体   繁体   中英

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. 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. 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. I have tried in a number of ways (two different AJAX requests, etc) but it doesn't work. 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.

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