如何用jQuery AJAX传参展示纪律守则列表?请求排查报错问题
Hey there, let's figure out why your AJAX call is hitting that error alert and not loading the discipline codes. I spot a few key issues in your code that we can fix step by step:
1. 修正location_id变量(最核心问题)
你现在写的var location_id = location;是把浏览器的整个window.location对象赋值给了变量,而不是表单里实际的location ID值。如果页面上有一个ID为location_id的输入/选择框(和你获取company_id的方式一致),把这行改成:
var location_id = $('#location_id').val();
2. 移除已废弃的async: false
同步AJAX请求(async: false)已经被浏览器废弃,还会导致页面在等待响应时卡顿。直接删掉这一行即可——AJAX默认就是异步的,去掉后代码运行会更流畅。
3. 增强错误调试能力
现在你的错误处理只有一个通用提示,我们可以添加控制台日志,查看具体的错误原因(比如服务器报错、JSON格式无效等):
error: function(xhr, status, error) { console.log('AJAX错误详情:', xhr.responseText, status, error); alert('无法获取数据,请查看浏览器控制台了解更多细节。'); }
按下F12打开浏览器开发者工具,切换到Console标签,就能看到请求失败时的完整错误信息。
4. 验证服务器端接口
确保你的PHP接口<?php echo base_url()?>app/code_of_discipline/showallcod满足:
- 能正确接收
company_id和location_id参数 - 返回有效的JSON格式数据(没有语法错误,且是你的success函数预期的对象数组)
修复后的完整代码
下面是应用了所有修复后的函数:
function showallcod() { var company_id = $('#company_id').val(); var location_id = $('#location_id').val(); // 修正location_id取值 $.ajax({ type: 'POST', // 备注:如果接口预期POST请求,建议显式指定 url: '<?php echo base_url()?>app/code_of_discipline/showallcod', data: { "company_id": company_id, "location_id": location_id }, dataType: 'json', success: function(datas) { var html = ''; var i; for (i = 0; i < datas.length; i++) { html += '<tr>' + '<td>' + datas[i].numbering + '</td>' + '<td>' + datas[i].title + '</td>' + '<td>' + datas[i].description + '</td>' + '<td>' + '<a href="javascript:;" class="btn btn-info">Edit</a>' + '<a href="javascript:;" class="btn btn-danger">Delete</a>' + '</td>' + '</tr>'; } $('#showdata').html(html); }, error: function(xhr, status, error) { console.log('AJAX错误详情:', xhr.responseText, status, error); alert('无法获取数据,请查看浏览器控制台了解更多细节。'); } }); }
另外别忘了检查页面上是否存在ID为location_id的元素(比如输入框或下拉选择器),并且它的取值是你需要发送的位置ID。
内容的提问来源于stack exchange,提问作者Khazlie Nemuel Lim

