如何使用JavaScript实现用户界面展示的表单空值错误提示功能
实现方案
你需要先在触发AJAX请求前做输入框非空校验,判断四个坐标输入框是否存在空值,存在的话直接弹出错误提示、终止请求即可,不要把校验逻辑放到请求的error回调里——该回调只会在请求本身发送失败(例如接口报错、跨域、网络异常)时触发,参数为空的正常请求不会进入该逻辑。
修改后的完整代码如下:
$("#btnWeatherRun").click(function () { // 先获取所有输入框的值,去除首尾空格 const northVal = $("#north").val().trim(); const southVal = $("#south").val().trim(); const eastVal = $("#east").val().trim(); const westVal = $("#west").val().trim(); // 非空校验,只要有一个为空就弹提示、终止后续逻辑 if(!northVal || !southVal || !eastVal || !westVal) { alert("所有坐标输入框不能为空,请填写完整后再提交"); return; } $.ajax({ url: "libs/php/weather.php", type: "GET", dataType: "json", data: { north: northVal, south: southVal, east: eastVal, west: westVal, }, success: function (result) { console.log(result); if (result.status.name == "ok") { $("#outputDate").html(result["data"]["weatherObservations"][0]["datetime"]); $("#outputStationName").html(result["data"]["weatherObservations"][0]["stationName"]); $("#outputTemperature").html(result["data"]["weatherObservations"][0]["temperature"]); $("#outputHumidity").html(result["data"]["weatherObservations"][0]["humidity"]); $("#outweatherCondition").html(result["data"]["weatherObservations"][0]["weatherCondition"]); $("#outputWindSpeed").html(result["data"]["weatherObservations"][0]["windSpeed"]); } }, error: function (jqXHR, textStatus, errorThrown) { // 请求本身出错时的提示 alert("请求数据失败,请稍后重试"); }, }); });
关键修改点说明
- 发起请求前先获取所有输入框的值,用
trim()去掉首尾空格,避免用户只输入空格的情况被判定为有效输入 - 对四个值做非空判断,任意一个为空就弹出提示,用
return终止后续的请求发送逻辑 - 移除原error回调里无效的空值判断逻辑,补充了请求异常时的通用提示
内容的提问来源于stack exchange,提问作者liam_303
相关产品推荐
相关产品推荐

