表单提交js和ajax新实现

<form id="formMain"  class="form-horizontal" method="post" action="<?=$baseUrl?>/updateItemDetail">
	<div class="main"> 主体内容 </div>
	<div class="box-footer" style="text-align: center">
		<button type="button" id="formBtn" class="btn btn-info" data-loading-text="<i class='fa fa-spinner fa-spin '></i>">
			确定
        </button>
        <button type="reset" class="btn btn-warning">
			取消
		</button>
    </div>
</form>
<script src="jquery-1.8.3.min.js"></script>

<script>
	/**
	* 表单数据提交
	*/
	$('#formBtn').click(function (event) {
        commitForm('formMain',_baseUrl,'post');
    });

	/**
	 * @theme 表单提交方法
	 * @param formID 要提交的表单 (表单id号)
	 * @param redirctUrl  跳转地址 (路由)
	 * @param method    提交的方式 (get|post)
	 * @param type 1 回退  2 跳转 3 局部加载
	 */
	function commitForm(formID, redirctUrl, method, type) {

		if (typeof (method) == 'undefined' || ['get', 'post'].indexOf(method) == -1) {
			method = 'post';
		}
		console.log(type)
		if (isNaN(type)) {
			type = 1;
		}

		var _form = $('#' + formID);
		$.ajax({

			url: _form.attr('action'),
			method: method,
			data: _form.serialize(),
			async: false,
			dataType: "json",
			timeout : 1000,
			headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
			success: function (data) {
				formRemoveClass();
				if (data.status == 200) {
					toastr.success(data.message);

					if (type == 1) {
						history.back(1);
					} else if (type == 2) {
						location.href = redirctUrl;
					} else {
						$.pjax.reload('#pjax-container');
					}

				} else if (data.status == 201) {

					if (typeof data.message == 'string') {
						toastr.warning(data.message);
					} else {
						for (k in data.message) {
							formAddClass(k);
							if (data.message[k].length > 1) {
								for (kk in data.message[k]) {
									toastr.warning(data.message[k][kk]);
								}
							} else {
								toastr.warning(data.message[k][0]);
							}

						}
					}

				} else {
					toastr.error(data.message);
				}
			},
			complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
				if(status=='timeout'){//超时,status还有success,error等值的情况
					ajaxTimeoutTest.abort();
					toastr.error('接口超时');
				}
			},
			error: function () {
				toastr.error('error');
			}
		});
	}
	/**
	 * 移除类
	 */
	function formRemoveClass() {
		$('div.form-group').removeClass('has-error');
	}

	/**
	 * 添加类
	 * @param fieldName
	 */
	function formAddClass(fieldName) {
		$('#' + fieldName).parent().parent('div.form-group').addClass('has-error');
	}

</script>
发布了59 篇原创文章 · 获赞 2 · 访问量 5600

猜你喜欢

转载自blog.csdn.net/LDR1109/article/details/79853607