Post JSON to Python CGI

后端 未结 2 1061
误落风尘
误落风尘 2020-11-30 09:17

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

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 09:45

    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\n\n'
    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.

提交回复
热议问题