gpt4 book ai didi

javascript - 页面加载时发生空请求时如何防止 500 GET 错误?

转载 作者:行者123 更新时间:2023-12-01 00:22:34 27 4
gpt4 key购买 nike

我有一个带有依赖下拉列表的表单,每当提交表单时都会加载该下拉列表,以便在表单提交之前选择的主要选择在提交后再次预加载。我注意到每当页面首次加载而没有传递参数时,我都会收到 GET: 500 Internal Server Error ,错误如下所示:

Internal Server Error: /operations/ajax/load-stations/

ValueError at /operations/ajax/load-stations/ invalid literal for int() with base 10: ''


Request URL: http://localhost:8000/operations/ajax/load-stations/?work_area=
Request Method: GET
Status Code: 500 Internal Server Error

因为当页面首次加载并且尚未提交任何表单时,work_area 为空(work_area = "")。如何修改 JS 或函数以避免出现此错误?

enter_exit.html

{% block main %}
<form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
{% csrf_token %}

<div>
<div>
<label>Employee #</label>
{{ form.employee_number }}

</div>

<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div id="my-hidden-div">
<label>Station</label>
{{ form.station_number }}
</div>
<!-- Rest of the form -->
</div>

</form>

<script>
function loadStations() {
var url = $("#warehouseForm").attr("data-stations-url");
var workAreaId = $(this).val();
var $stationNumberField = $("#{{ form.station_number.id_for_label }}");

$.ajax({
url: url,
data: {
'work_area': workAreaId
},
success: function (data) {
$("#my-hidden-div").show(); // show it
$stationNumberField.html(data);
// Check the length of the options child elements of the select
if ($stationNumberField.find("option").length === 1) {
$stationNumberField.parent().hide(); // Hide parent of the select node
} else {
// If any option, ensure the select is shown
$stationNumberField.parent().show();
}
}
});
}
$("#id_work_area").change(loadStations);
$("#id_work_area").change();
</script>

{% endblock main %}

views.py

def load_stations(request):
work_area_id = request.GET.get('work_area')
stations = Station.objects.filter(work_area_id=work_area_id).order_by('name')
return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations})

urls.py

urlpatterns = [
url(r'enter-exit-area/$', views.enter_exit_area, name='enter_exit_area'),

url(r'ajax/load-stations/$', views.load_stations, name='ajax_load_stations'),
]

最佳答案

最简单的方法是在启动 AJAX 请求之前测试 work_area 的值:

 if (workAreaId !== "") {
$.ajax({
url: url,
data: {
'work_area': workAreaId
},
success: function (data) {
$("#my-hidden-div").show(); // show it
$stationNumberField.html(data);
// Check the length of the options child elements of the select
if ($stationNumberField.find("option").length === 1) {
$stationNumberField.parent().hide(); // Hide parent of the select node
} else {
// If any option, ensure the select is shown
$stationNumberField.parent().show();
}
}
});
}

关于javascript - 页面加载时发生空请求时如何防止 500 GET 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290166/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com