我试图了解Ajax调用是如何工作的。
我将一个Json对象作为URL发送到一个瓶子python webservice。
@{ Html.RenderAction("Navigation", "Home"); }
上面的代码段是我的Ajax Call。 $.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")
},
});
是我打算发送到服务器的Json对象。
output
这是我的Web服务代码段。
我得到@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)
我一直在关注Bottle和Jquery文档,但我只是无法解决这个问题。 对此的任何帮助都会非常棒。
答案 0 :(得分:1)
考虑以下事项:
1)在JS中,将网址更改为:/salesvolume
。
2)在Python中,从db
函数定义中删除arg - 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>
希望它有所帮助!
答案 1 :(得分:0)
以下代码在使用bottle的app中为我工作(将一些数据发送到python并将一些数据作为JSON从python发送回js):
JS:
$.post('/getData', {myStringInput:dataToSendtoBottle}, function(data){
var myJson = JSON.parse(data) //myOutput is dispatched back to js as JSON
});
蟒:
@route('/getData', method='POST')
def getData():
myDataReceivedfromJs = request.forms.get('myStringIput')
if myDataReceivedfromJs:
myStringOutput = 'OK'
myOutput = json.dumps(myStringOutput)
return myOutput