我正在尝试了解 Ajax 调用的工作原理。
我将 Json 对象作为 URL 发送到 Bottle Python 网络服务。
$.ajax({
type: "POST",
data: {"jstring": JSON.stringify(output)},
url: "http://localhost:8080/salesvolume" ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#container').highcharts(data);
},
error: function() {
alert("Something is not OK")
},
});
上面的片段是我的 Ajax 调用。 output
是我打算发送到服务器的 Json 对象。
@app.post('/salesvolume')
def salesvolume(db):
jsonstring = request.forms.get('jstring')
_jsonparams = json.loads(jsonstring)
_studios = _jsonparams.Studios
ret = `Some Json`
return json.loads(ret)
app.run(server='paste', host='localhost', port=8080, debug=True, reloader=True)
这是我的网络服务代码片段。
我得到一个Status Code: HTTP/1.0 500 Internal Server Error
我一直在关注 Bottle 和 Jquery 文档,但我就是无法破解它。 在这方面的任何帮助都将非常有用。
最佳答案
考虑以下事项:
1) 在 JS 中,将 url 更改为:/salesvolume
.
2) 在 Python 中,删除 arg - db
来自 salesvolume
函数定义。否则您可能会遇到此错误(500
错误):
TypeError: salesvolume() takes exactly 1 argument (0 given)
<myServerIP> - - [30/Jul/2015 13:31:27] "POST /salesvolume HTTP/1.1" 500 1328
3) 检查缩进。是 python !我猜
ret = Some Json
和
return json.loads(ret)
需要缩进(它们应该在 salesvolume
函数内)
我写了类似的东西,它似乎在工作:
python :
from bottle import *
import json, requests
@route('/')
def atHome():
return template('index')
@route('/salesvolume', method="POST")
def salesvolume():
#your processings here...
ret = '{"key":"val"}'
return json.loads(ret)
run(host='0.0.0.0', port=8093, debug=True, reloader=True)
index.tpl 和 JS:
<html>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<body>
<button onclick=ajaxF()>click</button>
</body>
<script>
function ajaxF(){
$.ajax({
type: "POST",
data: {"jstring": JSON.stringify("blah")},
url: "/salesvolume" ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log('success');
console.log(data)
},
error: function() {
console.log("Something is not OK");
},
});
}
</script>
</html>
希望对您有所帮助!
关于python - Ajax:无法将 Json 对象发送到 Bottle Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31053423/