且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从python文件中的ajax发布请求获取发布数据

更新时间:2023-02-23 20:41:49

我设法提出了一个解决方案.我希望其他人也可以使用它.

通过以下python代码,我设法从ajax调用中获取postdata.

    def index(req):
        postData = req.form
        json = str(postData['param'].value)

I'm trying to post some data with an ajax post request and execute a python file, retrieving the data in the python file, and return a result.

I have the following ajax code

        $(function () {
                    $("#upload").on("click", function (e) {
                        $.ajax({
                            type: 'post',
                            url: "test1.py",
                            data: {'param1':'abc'},
                            async: false,
                            success: function (response) {
                                console.log(response);
                            }
                        }).done(function (data) {
                            console.log(data);
                        });
                    });
                });

And the following python file

    #! /usr/bin/python
    from __future__ import print_function
    import cgi, cgitb
    def index():
        data = cgi.FieldStorage()
        mydata = data['param1'].value
        return return "test"

I'm getting a keyerror on param1 -> "KeyError: 'param1'". I've also tried to use getValue(data['param1']. It looks like a problem with transferring the data from the ajax call to the python file i want to execute... But i can't figure out why.

Thanks in advance

I've managed to come up with an solution. I hope other people can get use of it as well.

By the following python code i've manged to get the postdata from the ajax call.

    def index(req):
        postData = req.form
        json = str(postData['param'].value)