You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:09:03