嗨,我想用django template
的ajax调用来调用我的django template
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)
我的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>
当我试图按下链接时,它返回以下错误:
ValueError: int()的无效文本,以10为基数:'object Object‘web_1 /24/9p/2019 03:13:14 "POST /ValueError/add_ValueError/object%20 object/ HTTP/1.1“500 ValueError
我试着把property_id变成一个字符串,看起来它仍然不起作用,我不知道我还错过了什么,我是jquery的菜鸟
谢谢你看了我的问题!
发布于 2019-09-24 06:52:03
我把我的脚本改为:
$('#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>
现在起作用了
https://stackoverflow.com/questions/58072638
复制相似问题