Is it possible to post an object from jquery to bottle.py?

我怕爱的太早我们不能终老 提交于 2019-12-24 01:55:14

问题


here is the jquery

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

Here is the python

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

It looks like the the url formats on support int, float, path, and re... am I missing something?


回答1:


There are only bytes on the wire. To send an object you need to serialize it using some data format e.g., 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);
    }
});

On the receiving end you need to parse json text into Python object:

from bottle import request, route

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

Returned dictionaries are automatically converted to json.




回答2:


It might not be that relevant, but the answer in short is No and Yes. If you're using the data attribute of jquery. It will actually transform your object into fields. Something like that:

{
  friend: [1,2,3]
}

May be sent as such to the server:

friend[0]=1&friend[1]=2&friend[2]=3

That said, HTTP doesn't actually define any "right" way to send data to the server. jQuery does that to make it works as if the client posted a form. So it is serializing data like formdata.

But that's not all! Since you can send data as you like. You can do something different. I'm not sure it is possible to send raw data with jQuery.

You might want to try that:

$.ajax({
  url: ...,
  data: myObject.toJSON(),
  ...
})

Since you're sending a string without any defined fields. You'll have to check on the server for the raw data. Convert the JSON string to a dict and you're good to go.

To make sending json to your server, there is a fabulous thing called, jsonrpc.

http://www.jsonrpc.org/

Unfortunately my knowledge of bottle.py is close to 0 so I can't really help much on how to get data.

tldr

Send json to the server and then parse it back to a dict, you could send anything else as long as you know how to parse it back on the other side. (xml, json, messagepack...)



来源:https://stackoverflow.com/questions/12811231/is-it-possible-to-post-an-object-from-jquery-to-bottle-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!