我看过许多答案,展示了如何使用python方法访问json但是我似乎无法让我的工作。
这是我的ajax电话
var data = {
'customer': customer,
'custID': custID,
'date': date,
'jobNum': jobNum,
'deviceID': deviceID
}
//create customer
if (custID === undefined) {
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
}
else {
//empty
}
这是我的python方法:
@view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
response = request.POST
myObject = json.loads(response)
#print myObject["customer"]
test = "hello"
return dict(test=test)
对python来说有点新,所以请原谅我有限的理解。如何获取我的json并访问对象属性?当我尝试打印时,我进入cmd的所有内容都是ValueError: No JSON object could be decoded
答案 0 :(得分:2)
pyramid
具有本机JSON请求支持。将contentType
参数设置为application/json
以告知服务器您正在发送JSON,最好使用字符集(UTF8):
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
并在服务器端使用request.json_body
:
@view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
myObject = request.json_body
print myObject["customer"]
test = "hello"
return dict(test=test)