嗨,我正在尝试用来自我django api
的 ajax 电话给我打电话django template
API 接收一个 POST 请求,在 url 中包含一个 id 值
我的 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/Sep/2019 03:13:14] "POST /api/add_favorite/[object%20Object]/ HTTP/1.1" 500 17473
我试图把 property_id 变成一个字符串,看起来它仍然不起作用,我不知道我还缺少什么。我是 jquery 的菜鸟
感谢您阅读我的问题!
我将脚本更改为:
$('#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>
现在它起作用了
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句