简体   繁体   中英

GET return value from Python via Javascript Ajax

I'm trying to write a Javascript program which can get the return value of my Python program, I'm using Ajax. The connect between Js and Python succeeded, but when I use alert() function in Javascript to show what I got, It shows that it is always the whole Python code, not the return value I want. I tried several different Python programs, the returns are always the Python program itself. I need to get the return value, ({"a":"15","b":"17"} in this example).

Here is the Ajax part in Javascript:

$.ajax({
    type: "get",
    url: "http://localhost:8000/test.py",
    data: {a:"15",b:"20"},
    datatype: "json",
    success: function(response){
        var output = response;
        alert(output);
        //var getvalue = output.startdate;
        //var xxx = parseInt(getvalue);
    }
})

Here is the Python program:

import cgi, cgitb
import json
import sys

def TryAgain():
    data = cgi.FieldStorage()
    output = {"a":"15","b":"17"}
    return output

Here is the running result on website: http://i.stack.imgur.com/HZr34.png

So, it looks like the problem here is that you aren't actually serving python code, but rather the file where that code resides. Your server needs another layer sitting between the code and the request that lets it understand how to translate the request into a specific function to run.

Typically, the way python users handle this is by integrating their server code into a web framework like Flask or Pyramid .

If you're also using a webserver for HTML content (which I assume you are, given that the file was reachable at all), you may need to additionally investigate using one more layer, that tells the webserver when to send things to your web framework rather than trying to service them itself. This layer is called WSGI , and most web frameworks will have specific guides with instructions on how to implement WSGI for your particular constellation of technologies.

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