当前位置:Gxlcms > JavaScript > jquery实现ajax提交表单信息的简单方法(推荐)

jquery实现ajax提交表单信息的简单方法(推荐)

时间:2021-07-01 10:21:17 帮助过:11人阅读

最近在思考优化项目,想自己扩展一个jquery自动获取表单中的数据进行ajax提交。本人没有完整性学习jquery,基本上是现学现找,有点困难。

主要是扩展和拼接json转对象

很简单,附上代码:

  1. ; (function ($) {
  2. $.fn.ajaxForm = function (options) {
  3. var defaults = {
  4. modelname: 'model',//后台对象接收名称
  5. url: '/',//提交地址
  6. postType: 'POST',//提交方式
  7. dataType: 'JSON',//数据返回类型
  8. async: false,//是否异步
  9. optionObj: [],//自定义参数
  10. callback: function () { },//成功回调
  11. };
  12. var options = $.extend(defaults, options);//合并参数
  13. if (options.url == '') {
  14. alert('请填写提交地址');
  15. return;
  16. }
  17. var postvals = {};
  18. //textbox/隐藏域/textarea/radio选中值
  19. $(this).find('input[type="text"],input[type="hidden"],textarea,input[type="radio"]:checked').each(function () {
  20. if ($(this).val() != undefined) {
  21. var name = $(this).attr('name');
  22. if (name == undefined || name == '') {
  23. return false;
  24. }
  25. var value = $(this).val();
  26. var json = '{"' + name + '":"' + value + '"}';
  27. var obj = $.parseJSON(json);
  28. postvals = $.extend(postvals, obj);
  29. }
  30. });
  31. var resObj;
  32. if (options.optionObj != undefined || options.optionObj!=[]) {
  33. resObj = $.extend(postvals,options.optionObj);
  34. } else {
  35. resObj = postvals;
  36. }
  37. $.ajax({
  38. type: options.postType,
  39. dataType: options.dataType,
  40. data: resObj,
  41. async: options.async,
  42. url: options.url,
  43. success: function (json) {
  44. if (json.IsError) {
  45. alert(json.Message);
  46. } else {
  47. options.callback();
  48. }
  49. }
  50. });
  51. };
  52. })(jQuery);

使用的话配合jquery validate使用

  1. $("#system-form").validate({
  2. rules: {
  3. SystemName: {
  4. required: true
  5. },
  6. Description: {
  7. required: true,
  8. },
  9. },
  10. messages: {
  11. SystemName: {
  12. required: "请填写系统名称"
  13. },
  14. Description: {
  15. required: "请填写系统描述"
  16. }
  17. },
  18. submitHandler: function(form) {
  19. var url = '/oa/system/' + $(form).attr('ftype');
  20. $(form).ajaxForm({ url: url,modelname:'system', callback: function() {
  21. location.href = '/oa/system/index.html';
  22. } });
  23. }
  24. });

以上这篇jquery实现ajax提交表单信息的简单方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

人气教程排行