AJAX请求无响应:.done()未执行,出现NS_BINDING_ABORTED错误
问题根源与解决方案
核心问题:AJAX请求被页面跳转强制中断
你代码里的$(location).prop('href', '/index.php?view=loggedin')和location.reload()是在AJAX请求发起后立刻执行的——AJAX是异步操作,此时请求还在等待后端响应,页面跳转直接中止了未完成的请求,这就是NS_BINDING_ABORTED错误的原因。
修复步骤:
把页面跳转逻辑移到AJAX回调内
只有当AJAX拿到后端响应后,再根据返回的状态决定是否跳转或提示错误,不要在请求发起后立刻强制跳转。优化AJAX参数写法
- URL末尾的多余问号去掉,POST请求不需要在URL拼接参数
- data参数用对象形式,避免字符串拼接的编码问题,jQuery会自动处理表单编码
防止按钮默认行为
如果按钮在<form>标签内,点击会触发表单默认提交(刷新页面),需要在点击事件里阻止这个行为。
修正后的前端代码:
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- Bootstrap core JavaScript--> <script src="../resources/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../resources/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../resources/js/sb-admin-2.min.js"></script> <script> $(document).ready(function() { $("#btnLogin").click(function(event) { // 阻止按钮默认提交行为(如果在表单内) event.preventDefault(); console.log('clicked'); var uname = document.getElementById('inpUsername').value; var pwd = document.getElementById('inpPassword').value; $.ajax({ type: 'POST', url: 'resources/php/functions/main-functions.php', // 去掉末尾多余的问号 data: { // 用对象形式传递参数 inpUsername: uname, inpPassword: pwd }, dataType: 'json' }) .done(function(data, textStatus, jqXHR){ console.log('Response received:', data); if (data.status === 'success') { console.log('Authentication successful:', data.message); // 验证成功后再跳转 $(location).prop('href', '/index.php?view=loggedin'); } else { console.log('Authentication failed:', data.message); // 这里可以给用户显示错误提示,比如弹窗或页面内的提示框 } }) .fail(function(jqXHR, textStatus, errorThrown){ console.log('AJAX Error:', textStatus); console.log('Error details:', errorThrown); // 请求失败时的处理,比如提示用户网络问题 }); // 移除这里的跳转和刷新代码 }); }); </script>
后端PHP代码优化(处理空参数的情况)
当前代码在没有收到inpUsername或inpPassword时没有返回任何内容,建议补充处理,避免前端AJAX解析失败:
<?php if(!empty($_POST['inpUsername']) && !empty($_POST['inpPassword'])){ if(authUser()) { header('Content-Type: application/json'); die(json_encode(['status' => 'success', 'message' => 'User authenticated'])); } else { header('Content-Type: application/json'); die(json_encode(['status' => 'error', 'message' => 'Invalid credentials'])); } } else { // 处理参数为空的情况,返回JSON格式错误 header('Content-Type: application/json'); die(json_encode(['status' => 'error', 'message' => 'Missing username or password'])); } ?>
验证方法
修改后,点击登录按钮:
- 控制台会先输出
clicked,然后等待后端响应 - 收到响应后根据状态输出对应日志,验证成功才会跳转页面
- 不会再出现
NS_BINDING_ABORTED错误
内容的提问来源于stack exchange,提问作者Luigi
相关产品推荐
相关产品推荐

