How to receive JSON in a POST request in CherryPy?

后端 未结 3 1609
闹比i
闹比i 2020-11-30 00:23

How to receive JSON from POST requests in CherryPy?

I\'ve been to this page, and though it does a good job explaining the API, its parameters, and what it does; I

3条回答
  •  情话喂你
    2020-11-30 00:52

    Python

    import cherrypy
    
    class Root:
    
        @cherrypy.expose
        @cherrypy.tools.json_out()
        @cherrypy.tools.json_in()
        def my_route(self):
    
            result = {"operation": "request", "result": "success"}
    
            input_json = cherrypy.request.json
            value = input_json["my_key"]
    
            # Responses are serialized to JSON (because of the json_out decorator)
            return result
    

    JavaScript

    //assuming that you're using jQuery
    
    var myObject = { "my_key": "my_value" };
    
    $.ajax({
        type: "POST",
        url: "my_route",
        data: JSON.stringify(myObject),
        contentType: 'application/json',
        dataType: 'json',
        error: function() {
            alert("error");
        },
        success: function() {
            alert("success");
        }
    });
    

提交回复
热议问题