Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

jquery - Post JSON to Python CGI

I have got Apache2 Installed and Python working.

I am having a problem though. I have two pages.

One a Python Page and the other an Html Page with JQuery

Can someone please tell me how I can get my ajax post to work correctly.

<html>
<head>

</head>
<body>
<script>
    $(function()
    {
        alert('Im going to start processing');

        $.ajax({
            url: "saveList.py",
            type: "post",
            data: {'param':{"hello":"world"}},
            dataType: "application/json",
            success : function(response)
            {
                alert(response);
            }
        });
    });
</script>
</body>
</html>

And the Python Code

import sys
import json

def index(req):
    result = {'success':'true','message':'The Command Completed Successfully'};

    data = sys.stdin.read();

    myjson = json.loads(data);

    return str(myjson);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OK, let's move to your updated question.

First, you should pass Ajax data property in string representation. Then, since you mix dataType and contentType properties, change dataType value to "json":

$.ajax({
    url: "saveList.py",
    type: "post",
    data: JSON.stringify({'param':{"hello":"world"}}),
    dataType: "json",
    success: function(response) {
        alert(response);
    }
});

Finally, modify your code a bit to work with JSON request as follows:

#!/usr/bin/python

import sys, json

result = {'success':'true','message':'The Command Completed Successfully'};

myjson = json.load(sys.stdin)
# Do something with 'myjson' object

print 'Content-Type: application/json

'
print json.dumps(result)    # or "json.dump(result, sys.stdout)"

As a result, in the success handler of Ajax request you will receive object with success and message properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...