js之ajax一步到位

*、ajax调用语法

$.ajax({//ajax异步获取数据
	type:'POST',//请求方式
	dataType:'json',//返回数据格式,若该格式不指定为json那么下面获取的data数据仅是普通的字符串
	url: '<%=request.getContextPath()%>/yourAction.do?method=yourmethod&curLevel='+curLevel, 
	success: function(data){//根据设置的数据格式返回的结果
	    var option = "";
	    $("#upId").html("");//清空原有数据
		$.each(data, function (n, st) {//解析数据,html拼接
	       option += "<option value='"+st.id+"'>"+st.specialName + "</option>";
	   });
	   $("#upId").append(option);
	}
});

*、ajaxSubmit调用语法

jQuery(document.getElementsByName('yourForm')).ajaxSubmit( {//获取某表单
    dataType:'json',//返回信息的类型,若该格式不指定为json那么下面获取的data数据仅是普通的字符串
    success : function(data) {
	if (data.success) {//直接作为json对象使用即可
	    alert(data.msg);
		
	} else {
	    alert(data.msg);
	}
    }
});

*、后台要做点什么呢?

后台处理借用net.sf.json.JSON*等类将实体对象转为json对象的字符串以流的形式返回前台即可;
如:
response.setHeader("Content-type", "text/html");
response.setCharacterEncoding(charset);
response.getWriter().flush();
response.getWriter().print(JSON*类.fromObject(实体对象).toString());

----------------------------------------------------------小意外----------------------------------------------------------------

*、当ajax点击后无反应仔细查看error函数返回的内容

 error: function (xhr) {alert(xhr.responseText) }
扫描二维码关注公众号,回复: 297065 查看本文章

猜你喜欢

转载自lbovinl.iteye.com/blog/2369144