Django Ajax 表单在 "success" 后提交重新加载
Django Ajax Form submit reloads after "success"
从我之前的 post 扩展,包含 django 和 ajax (Django Ajax Image submit) 的问题,正如编辑中提到的,我遇到了以下情况:
我的 jquery/ajax 电话:
<script>
$(document).ready(function () {
// This jquery changes the appearance of the django { form_image }
var imgElement = $('#id_image');
imgElement.css('visibility', 'hidden');
console.log($('#id_image').attr('type'))
// This function triggers the hidden submit,
// which triggers the ajax image request
imgElement.on({
change: function () {
$('#hidden-submit-img').click();
},
});
});
// This jquery is for the ajax post of the image
// Doing it with submit, the image wont get saved, but the request is "success"
// $('#image_form').submit(function (event) {
// Doing it with change, the image gets saved successfully, but the respond loads a new page
$('#image_form').change(function (event) {
event.preventDefault();
$.ajax({
data: {
image: $('#id_image').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
enctype: $(this).attr('enctype'),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
console.log(1);
},
error: function () {
console.log(0);
}
});
});
</script>
如评论中所述,存在这种奇怪的行为,要么页面不会重新加载但图像不会保存,要么图像已保存但页面呈现为仅包含 "success" 的白页。我可以看到,console.log(1)
实际执行了,然后加载了白页。
我试图让我的文件尽可能简单。
这是我在 views.py 中的观点:
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
ImagesUpload.objects.create(
image = image,
)
return HttpResponse('success')
models.py:
class ImagesUpload(models.Model):
image = models.ImageField(upload_to=renaming_file)
def __str__(self):
return str(self.image)
home.html:
<form id="image_form" method="post" enctype="multipart/form-data" action="{% url 'website:image-feedback' %}">{% csrf_token %}
<button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button>
{{ form_image.image }}
<input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden">
</form>
我想我已经接近解决方案了,但也许我的技能还不够。
我想上传一张图片,将其存储在我的数据库中并让我的网站在没有 reloading/refreshing 的情况下继续运行。
你的 html 表格
<form id="image_form"> #does not provide any attribute
{% csrf_token %}
{{ form_image.image }}
</form>
jquery
将 jquery 放在表单
所在的同一页面
<script>
$("#id_image").change(function(){ // here my second change apply id of image field
var formdata = new FormData(); //create formdata object
formdata.append('image',this.files[0])
formdata.append('csrfmiddlewaretoken',$('input[name=csrfmiddlewaretoken]').val()); //apply csrf token
$.ajax({
url:"{% url 'website:image-feedback' %}",
method:'POST',
data:formdata,
enctype: 'application/x-www-form-urlencoded',
processData:false,
contentType:false,
success:function(data){
//update src attribute of img tag
$('#profile_pic').attr('src',data.url);
$('#image_form').trigger('reset'); // This reloads the form for additional upload
},
error:function(error){
//display error base on return the view
alert(error.error)
}
});
return false;
});
</script>
您的看法
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
img = ImagesUpload.objects.create(
image = image,
)
return JsonResponse(status=200,data={"url": img.url}) #return json response
else:
return JsonResponse(status=203,data={"error": "unauthorized request.!!"})
我提供了很多你看到的东西并在你的代码中应用然后打开 firefox 浏览器在检查元素的网络选项卡中查看 return 你的状态代码查看哪个状态代码 return 如果任何错误
从我之前的 post 扩展,包含 django 和 ajax (Django Ajax Image submit) 的问题,正如编辑中提到的,我遇到了以下情况:
我的 jquery/ajax 电话:
<script>
$(document).ready(function () {
// This jquery changes the appearance of the django { form_image }
var imgElement = $('#id_image');
imgElement.css('visibility', 'hidden');
console.log($('#id_image').attr('type'))
// This function triggers the hidden submit,
// which triggers the ajax image request
imgElement.on({
change: function () {
$('#hidden-submit-img').click();
},
});
});
// This jquery is for the ajax post of the image
// Doing it with submit, the image wont get saved, but the request is "success"
// $('#image_form').submit(function (event) {
// Doing it with change, the image gets saved successfully, but the respond loads a new page
$('#image_form').change(function (event) {
event.preventDefault();
$.ajax({
data: {
image: $('#id_image').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
enctype: $(this).attr('enctype'),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
console.log(1);
},
error: function () {
console.log(0);
}
});
});
</script>
如评论中所述,存在这种奇怪的行为,要么页面不会重新加载但图像不会保存,要么图像已保存但页面呈现为仅包含 "success" 的白页。我可以看到,console.log(1)
实际执行了,然后加载了白页。
我试图让我的文件尽可能简单。
这是我在 views.py 中的观点:
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
ImagesUpload.objects.create(
image = image,
)
return HttpResponse('success')
models.py:
class ImagesUpload(models.Model):
image = models.ImageField(upload_to=renaming_file)
def __str__(self):
return str(self.image)
home.html:
<form id="image_form" method="post" enctype="multipart/form-data" action="{% url 'website:image-feedback' %}">{% csrf_token %}
<button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button>
{{ form_image.image }}
<input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden">
</form>
我想我已经接近解决方案了,但也许我的技能还不够。
我想上传一张图片,将其存储在我的数据库中并让我的网站在没有 reloading/refreshing 的情况下继续运行。
你的 html 表格
<form id="image_form"> #does not provide any attribute
{% csrf_token %}
{{ form_image.image }}
</form>
jquery 将 jquery 放在表单
所在的同一页面<script>
$("#id_image").change(function(){ // here my second change apply id of image field
var formdata = new FormData(); //create formdata object
formdata.append('image',this.files[0])
formdata.append('csrfmiddlewaretoken',$('input[name=csrfmiddlewaretoken]').val()); //apply csrf token
$.ajax({
url:"{% url 'website:image-feedback' %}",
method:'POST',
data:formdata,
enctype: 'application/x-www-form-urlencoded',
processData:false,
contentType:false,
success:function(data){
//update src attribute of img tag
$('#profile_pic').attr('src',data.url);
$('#image_form').trigger('reset'); // This reloads the form for additional upload
},
error:function(error){
//display error base on return the view
alert(error.error)
}
});
return false;
});
</script>
您的看法
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
img = ImagesUpload.objects.create(
image = image,
)
return JsonResponse(status=200,data={"url": img.url}) #return json response
else:
return JsonResponse(status=203,data={"error": "unauthorized request.!!"})
我提供了很多你看到的东西并在你的代码中应用然后打开 firefox 浏览器在检查元素的网络选项卡中查看 return 你的状态代码查看哪个状态代码 return 如果任何错误