通过Javascript Ajax从Python获取返回值 [英] GET return value from Python via Javascript Ajax

查看:860
本文介绍了通过Javascript Ajax从Python获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个Javascript程序,该程序可以获取我的Python程序的返回值,而我正在使用Ajax. Js和Python之间的连接成功,但是当我使用Javascript中的alert()函数显示所得到的内容时,它表明它始终是整个Python代码,而不是我想要的返回值.我尝试了几种不同的Python程序,返回值始终是Python程序本身.我需要获取返回值(在此示例中为{{"a":"15","b":"17"}).

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

这是Javascript中的Ajax部分:

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);
    }
})

这是Python程序:

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:

推荐答案

因此,这里的问题似乎是您实际上不是在为服务 python代码,而是该代码所在的文件居住.您的服务器需要位于代码和请求之间的另一层,以便它了解如何将请求转换为要运行的特定功能.

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.

通常,python用户处理此问题的方法是将其服务器代码集成到 web框架中,例如金字塔.

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

如果您还将Web服务器用于HTML内容(假设文件完全可以访问,我想是可以的),则可能需要另外再调查一层,告诉Web服务器何时发送内容到您的Web框架,而不是尝试自己提供服务. 此层称为WSGI ,以及大多数网络框架将有具体的指南,其中包含有关如何为您的特定技术群实施WSGI的说明.

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.

这篇关于通过Javascript Ajax从Python获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆