【发布时间】:2021-06-05 14:04:52
【问题描述】:
我使用 Django2 开发了一个网络应用程序。 我在前端,在 ajax 调用之后,chrome dev 上的网络选项卡确实显示了 200 状态代码,但我没有看到任何警报框。我的应用卡在这条线上等待 json: const msg_json = await response.json(); ,以下警报不会执行
async function myFunction() {
Swal.fire({
title: '',
text: "Do you want to confirm entries?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then(
async(result) => {
if (result.value) {
$.ajax({
url: '/content_checklist_name_url/',
type: 'POST',
data: $(this).serialize(),
cache: false,
success: function(data) {
var comment_html = "<div id='myform_1'>" + data['log_info'] + "</div>";
$('#myform_1').remove();
$('#ajax_data').prepend(comment_html);
$('#myform_input').val('');
},
});
const response = await fetch({ % url 'bms:content_checklist_name_url' %
});
const msg_json = await response.json();
alert(msg_json.responseText)
let a = msg_json;
if (a === "Duplicate Entry. This Course Code already exists.") {
Swal.fire({
title: '',
text: 'Duplicate Entry. This Course Code already exists.',
type: 'error',
})
} else {
Swal.fire({
title: '',
text: 'Entries have been saved.',
type: 'success',
})
}
// },
// failure: function(data)
// {
// alert('Got an error dude');
// }
// });
} else {
window.stop();
}
}
)
}
<form id="myform" action="/content_checklist_name_url/" method="POST">
...
</form>
<button class="button" onclick="myFunction()" type="button" id="submit">SUBMIT</button>
后端视图.py:
@csrf_exempt
def content_checklist_name_url(request):
if request.method == 'POST':
...
msg = "success"
obj = {"msg": msg}
context = {'msg_json': json.dumps(obj)}
return render(request, 'bms/main.html',context=context)
我在控制台中收到错误:VM355:4 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 3
不显示警告框。
我如何检查哪里出了问题?
【问题讨论】:
-
myFunction()在哪里以及如何被调用? ajax 应该在表单提交处理程序中。你打电话.submit()然后调用ajax。这个顺序没有意义 -
你应该转储 jQuery 的
$.ajax并改用原生的fetch。const response = await fetch(url); const msg_json = await response.json();工作完成 -
@JeremyThille 更新了我的问题,使用你的方法产生了新问题
-
呃?你没有使用我的方法。您仍在同时使用
$.ajax和await fetch。
标签: javascript django ajax