Python Django模板对api的ajax调用-int()的文本无效,基数为10:';[对象对象]';
您好,我正试图使用来自我的Python Django模板对api的ajax调用-int()的文本无效,基数为10:';[对象对象]';,python,jquery,django,ajax,api,Python,Jquery,Django,Ajax,Api,您好,我正试图使用来自我的django模板的ajax调用调用我的django api API接收一个带有url中id值的POST请求 我的api视图: @api_view(['POST']) def add_favorite(request, property_id): if request.method == 'POST': try: favorite_property = Property.objects.get(pk=property_id)
django模板的ajax调用调用我的django api
API接收一个带有url中id值的POST请求
我的api视图:
@api_view(['POST'])
def add_favorite(request, property_id):
if request.method == 'POST':
try:
favorite_property = Property.objects.get(pk=property_id)
if request.user.is_authenticated:
login_user = request.user
if not login_user.properties.filter(pk=property_id).exists():
login_user.properties.add(favorite_property)
return JsonResponse({'code':'200','data': favorite_property.id}, status=200)
else:
return JsonResponse({'code':'404','errors': "Property already exists in favorite"}, status=404)
except Property.DoesNotExist:
return JsonResponse({'code':'404','errors': "Property not found"}, status=404)
My html与ajax调用的锚链接:
<a id="mylink" href="javascript:onclickFunction('{{ property.id }}')">
<i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i>
</a>
这就是我在django视图中调用API以尝试获得响应的方式:
<script>
$(document).ready(function () {
$('#mylink').on('click', function (property_id) {
property_id.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:9999/api/add_favorite/" + property_id.toString() + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
var obj = jQuery.parseJSON(data);
alert(obj);
}
});
return false;
});
});
</script>
$(文档).ready(函数(){
$('#mylink')。在('click',函数(属性id){
属性_id.preventDefault();
$.ajax({
类型:“POST”,
url:“http://localhost:9999/api/add_favorite/“+属性\u id.toString()+”/“,
发送前:函数(xhr){
setRequestHeader('Authorization','Bearer{{refresh_token}}}');
},
成功:功能(数据){
var obj=jQuery.parseJSON(数据);
警报(obj);
}
});
返回false;
});
});
当我尝试按下链接时,它返回以下错误:
ValueError:基数为10的int()的文本无效:“[object]”
web_1|[24/Sep/2019 03:13:14]“POST/api/add_favorite/[object%20Object]/HTTP/1.1”500 17473
我试图将属性id转换为字符串,但似乎它仍然不起作用,我不知道我还遗漏了什么。我是jquery的一个noob
谢谢你阅读我的问题 我将脚本更改为:
$('#mylink').on('click', function (event) {
event.preventDefault();
property_id = $(this).attr("value")
$.ajax({
type: "POST",
url: "http://localhost:9999/api/add_favorite/" + property_id + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
if (data.code == 200) {
alert('ok');
}
}
});
return false;
});
和我的html地址:
<a id="mylink" href="javascript:onclickFunction()" value="{{ property.id }}">
<i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i>
</a>
它现在起作用了