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

如何在现有jQuery表单Ajax代码中实现指定class的div局部刷新

实现方法

你只需要调整两处代码就可以实现需求,逻辑非常简洁:

  1. 先确保你的form提交对应的后端接口,在处理完提交请求后,返回指定class的div需要展示的最新HTML片段即可,不需要返回完整页面。
  2. 调整你的JS代码,补全success回调的参数,加上替换元素内容的逻辑即可,示例中我们假设你要刷新的div的class为need-refresh,你可以替换成自己实际使用的class名。

修改后的完整代码如下:

$('form').on('submit', function() {
  var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};
  that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();
      data[name] = value;
  });

  $.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {
      // 仅需这一行即可完成指定class元素的局部刷新
      $('.need-refresh').html(response);
    }
  });
  return false;
});

如果你的后端返回的是JSON格式数据,需要自己拼接HTML再替换,写法如下:

success: function(response) {
  // 示例:假设返回的JSON里有title、content两个字段,自己拼接成需要的HTML结构
  var newHtml = `<h3>${response.title}</h3><p>${response.content}</p>`
  $('.need-refresh').html(newHtml);
}

内容的提问来源于stack exchange,提问作者johnnyjohn400

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:48:03