使用JavaScript从阿贾克斯蟒蛇code蟒蛇、JavaScript、阿贾克斯、code

2023-09-10 18:11:48 作者:自个儿的心自个儿疼

我已经看到了这个话题: Ajax请求python脚本他们试图这样做正是我需要的,但有一个信息丢失。

I have seen this topic: ajax request to python script where they were trying to do exactly what I need but there is one information missing.

$。员额('myPythonFile.py',{}数据,                       功能(结果){                           //去做                       }             );

$.post('myPythonFile.py',{data}, function(result){ //TODO } );

现在我的问题是:我怎么调用某个函数里面myPythonFile.py?有没有一种方法来指定函数的名称,并给它我输入的数据? 非常感谢您的宝贵时间。

Now my problem is: how do I call a certain function which is inside myPythonFile.py? Is there a way to specify the name of the function and to give it my input data? Thank you very much for your time.

推荐答案

阿贾克斯电话拨打 HTTP 请求,所以你需要有一个 HTTP服务器它处理,因为它被认为是在其他问题您的要求。 (有CGI它提供HTTP请求处理)。在Python中,你可以使用Django,瓶,CGI等有HTTP请求处理。从javascript调用Python函数。

Ajax calls making HTTP requests,so you need to have a HTTP server which handles your requests as it is seen in the other question. (There is CGI which provide HTTP request handling). In Python you can use DJango, Bottle, CGI etc to have HTTP request handling. to call python function from javascript.

url.py 你应该定义你的API URL;

in your url.py you should define your api url;

(r'^myAPI', 'myAPI'),

和这个URL,你应该在 views.py 的Web API。它可以像;

and on this url you should have a web API in views.py. It can be like ;

def myAPI(request):
    callYourFunction();

,你可以从现在的Javascript调用它。您可以使用jQuery的AJAX请求;

and you can call it from Javascript now. You can use JQuery for AJAX request;

 $.ajax({
            type:"GET",
            url:"/myAPI",
            contentType:"application/json; charset=utf-8",
            success:function (data) {     
            },
            failure:function (errMsg) {
            }
        });

HTTP 方法类型并不重要,如果你只是想运行一个的Python 脚本。如果你想从的JavaScript 将数据发送到的Python 您可以发送数据 JSON 来Python作为 POST 方法。

The HTTP method type does not matter, if you only wanna run a Python script. If you wanna send data from javascript to Python you can send the data as JSON to Python as POST method.