我正在使用带有 Ajax 的 Django,我已经使用 Ajax 成功上传了图像。
现在我想弄清楚如何使用 Ajax 直接更改图像 url。
html:
{% block content %}
<div class="row">
{{user.username}}
{{user.avatar.url}}
<p id="error"></p>
<div class="col-md-2">
<img class="avatar" src="{{user.avatar.url}}" width="60px" height="60px" />
</div>
<div class="mb-2"></div>
{% if request.user.username == profile_user.username %}
<form enctype="multipart/form-data" class="form-horizontal" method="post">
{% csrf_token %}
<label for="avatar" class="change-avatar" >更换头像/change avatar</label>
<input type="file" id="avatar" style="visibility:hidden;">
<input type="button" class="btn" value="保持更改/save">
</form>
<script>
$(".btn").click(
function(){
var formdata = new FormData();
formdata.append("avatar",$("#avatar")[0].files[0]);
$.ajax({
url:"",
type:"post",
contentType:false,
processData:false,
data:formdata,
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success:function(data){
console.log(data)
var error = data.error
var avatar = data.avatar
var s =`<div> ${error} </div>`
var t = '${avatar}'
var src = $(".avatar").attr('src').replace('avatar','avatar')
$(".avatar").attr('src', src);
$("#error").prepend(s);
}
})
}
)
</script>
{% endif %}
</div>
{% endblock content %}
意见:
@login_required
def user_detail(request, username):
profile_user = get_object_or_404(User, username=username)
form = UserAvatar(request.POST, request.FILES, instance=request.user)
response = {}
if request.is_ajax():
if form.is_valid():
form.save()
response['avatar'] = request.FILES.get('avatar')
else:
response['error'] = '格式错误'
return JsonResponse(response)
return render(request, 'user/user_detail.html', {
'profile_user': profile_user,
})