如何在现有jQuery表单Ajax代码中实现指定class的div局部刷新
实现方法
你只需要调整两处代码就可以实现需求,逻辑非常简洁:
- 先确保你的form提交对应的后端接口,在处理完提交请求后,返回指定class的div需要展示的最新HTML片段即可,不需要返回完整页面。
- 调整你的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
相关产品推荐
相关产品推荐

