是否可以将对象从jquery发布到bottle.py?

Joh*_*ohn 2 python jquery bottle

这是jquery

$.ajax({
    type: "POST",
    url: "/posthere",
    dataType: "json",
    data: {myDict:{'1':'1', '2':'2'}},
    success: function(data){
        //do code
    }
});
Run Code Online (Sandbox Code Playgroud)

这是蟒蛇

@route("/posthere", method="POST")
def postResource(myDict):
    #do code
    return "something"
Run Code Online (Sandbox Code Playgroud)

它看起来像支持int,float,path和re的url格式...我错过了什么?

jfs*_*jfs 7

电线上只有字节.要发送一个对象,您需要使用某种数据格式序列化它,例如,json:

$.ajax({
    type: "POST",
    url: "/posthere",
    data: JSON.stringify({myDict: {'1':'1', '2':'2'}}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        alert(data);
    },
    failure: function(err) {
        alert(err);
    }
});
Run Code Online (Sandbox Code Playgroud)

在接收端,您需要将json文本解析为Python对象:

from bottle import request, route

@route("/posthere", method="POST")
def postResource():
    #do code
    myDict = request.json['myDict']
    return {"result": "something"}
Run Code Online (Sandbox Code Playgroud)

返回的词典会自动转换为json.