1

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: https://i.stack.imgur.com/HZr34.png

Musa
  • 96,336
  • 17
  • 118
  • 137
Markieff
  • 21
  • 1
  • 2
  • 1
    You obviously need to tell your webserver to executy Python instead of returning the Python script content. While you posted all the Python stuff, nothing is known about your web server so far. Therefore, no answer can be given. – class stacker Dec 08 '15 at 14:46
  • @ClassStacker I see, but how to tell my webserver to executy Python? Maybe this question is too "basic". :) – Markieff Dec 08 '15 at 14:49
  • As I wrote, your question cannot be answered because you only provided all the information which is irrelevant. Ask a new one with a correct title, tags and content, or completely re-work this one. – class stacker Dec 08 '15 at 14:50

1 Answers1

0

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.

Community
  • 1
  • 1
mwobee
  • 524
  • 2
  • 7