企业开发中js,Jquery,Ajax和json格式的一个例子

本文介绍了一个用户添加功能的具体实现过程,包括HTML表单设计、JavaScript验证及AJAX异步保存等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以添加操作为例

1、

<div class="overlay" id="spm" style="display:none;"></div>
<div class="Popup" style="display:none">
   <div class="Popup_top"><h1>添加</h1><a href="#" class="Close"><img alt="关闭" src="../../images/close.png"/></a></div>
   <div class="Popup_cen">
       <table width="100%" border="0" cellspacing="0" cellpadding="0" class="BD_tab">
  <tr>
    <td style="width:110px;" align="right">姓名:</td>
    <td><input name="" id="name" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
  </tr>
  <tr>
    <td align="right">昵称:</td>
    <td><input name="" id="nickname" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
  </tr>
  <tr>
    <td style="width:110px;" align="right">账号:</td>
    <td><input name="" id="account" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
  </tr>
  <tr>
    <td align="right">密码:</td>
    <td><input name="" id="password1" type="password" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
  </tr>
  <tr>
    <td align="right">确认密码:</td>
    <td><input name="" id="password2" type="password" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
  </tr>
  <tr>
    <td align="right">性别:</td>
    <td><input type="radio" name="gender" value="0"/>男 
						<input type="radio" name="gender" value="1"/>女<font color="red">*</font>
    </td>
  </tr>
  <tr>
    <td align="right">出生日期:</td>
   <td><input id="birthDate" type="text" maxlength="10" onfocus="$(this).calendar()" readonly="readonly" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
 </tr>
  <tr>
  <td align="right" valign="top">简介:</td>
    <td><textarea name="" id="introduction" cols="" rows="" class="textarea220" onfocus="this.className='textarea220L';this.onmouseout=''" onblur="this.className='textarea220';this.onmouseout=function(){this.className='textarea220'};" onmousemove="this.className='textarea220Lg'" onmouseout="this.className='textarea220'"></textarea></td>
  </tr>
  <tr>
  	<td align="right" valign="top">省份:</td>
  	<td>
  		<select style="width:150px;"  id="cityBig" name="slt_category" onchange="onCityBig(this.value)">
				    <option value="">不限</option>
				    </select>
				    <font color="red">*</font>
  	</td>
  </tr>
  <tr>
  	<td align="right" valign="top">城市:</td>
  	<td>
  	<select style="width:150px;"  id="citySmall" name="slt_subcategory" onchange="onCitySmall(this.value)">
				    <option value="">不限</option>
				    </select>
				    <font color="red">*</font>
  	</td>
  </tr>
  <tr>
  	 <td align="right" valign="top">学校:</td>
    <td><input name="" id="school" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'">
    <font color="red">*</font></td>
  </tr>
  <tr>
  	 <td align="right" valign="top">住址:</td>
    <td><textarea name="" id="address" cols="" rows="" class="textarea220" onfocus="this.className='textarea220L';this.onmouseout=''" onblur="this.className='textarea220';this.onmouseout=function(){this.className='textarea220'};" onmousemove="this.className='textarea220Lg'" onmouseout="this.className='textarea220'"></textarea></td>
  </tr>
  <tr>
  	 <td align="right" valign="top">邮政编码:</td>
    <td><input name="" id="postCode" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'"></td>
  </tr>
  <tr>
  	 <td align="right" valign="top">座机号码:</td>
   <td><input name=""  id="landlineNumber" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'"></td>
  </tr>
  <tr>
  	 <td align="right" valign="top">手机号码:</td>
    <td><input name="" id="cellPhoneNumber" type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'"></td>
  </tr>
  <tr>
  	 <td align="right" valign="top">邮箱地址:</td>
   <td><input name="" id="email"  type="text" class="input220" onfocus="this.className='input220L';this.onmouseout=''" onblur="this.className='input220';this.onmouseout=function(){this.className='input220'};" onmousemove="this.className='input220Lg'" onmouseout="this.className='input220'"></td>
  </tr>
  <tr>
    <td align="right" valign="top">备注:</td>
    <td><textarea name="" id="remark" cols="" rows="" class="textarea220" onfocus="this.className='textarea220L';this.onmouseout=''" onblur="this.className='textarea220';this.onmouseout=function(){this.className='textarea220'};" onmousemove="this.className='textarea220Lg'" onmouseout="this.className='textarea220'"></textarea></td>
  </tr>
  <tr>
    <td align="right" valign="top"> </td>
    <td><input name="" id="addButton" type="button" class="jiansu" value="保存" onclick="addUser()"></td>
  </tr>
</table>

   </div>
</div>
2、

function saveInit(){
		$("#name").val("");
		$("#nickname").val("");
		$("#account").val("");
		$("#password1").val("");
		$('input[name=gender]:checked').attr('checked',false);
		$("#introduction").val("");
		$("#address").val("");
		$("#postCode").val("");
		$("#landlineNumber").val("");
		$("#cellPhoneNumber").val("");
		$("#school").val("");
		$("#email").val("");
		$("#birthDate").val("");
		$("#remark").val("");
        $("#cityBig").empty().append("<option value=\"\">不限</option>");
		$("#citySmall").empty().append("<option value=\"\">不限</option>");
		for(big in cityBig){
			$("#cityBig").append("<option value=\""+big+"\">"+cityBig[big]+"</option>");
		}
	}

3、

function addUser(){
	  $("#addButton").attr('disabled',true);//禁用按钮
	  if(userAddValidate){
		  //生日2014-04-30变成20140430
		  var birthday = $.trim($("#birthDate").val());
		  var birth = birthday.substring(0,4) + birthday.substring(5,7) + birthday.substring(8,10);
		  //searchModel与UserSearchModel.java中一致
		  var dataStr="{searchModel:{name:"+$.trim($("#name").val())
			  +",nickname:"+$.trim($("#nickname").val())
			  +",account:"+$.trim($("#account").val())
			  +",password:"+$.trim($("#password2").val())
			  +",gender:"+$.trim($("input[name='gender']:checked").val())
			  +",birthDate:"+birth
			  +",province:"+cityBigValue
			  +",city:"+citySmallValue
			  +",school:"+$.trim($("#school").val())
			  +",type:"+$("#selectUser").val()
			  +",createUserId:"+0;
	    dataStr=giveNull(dataStr);
		var suffix="}}";
		dataStr=dataStr+suffix;
		var url="../../webservice/user/user/userAdd";
		save(url,dataStr);
	  }else{
		  $("#addButton").removeAttr("disabled");
	  }
	}

4、

function save(url,dataStr){
			$.ajax({
				type:"POST",
				url:url,
				data:dataStr,
				contentType:"application/json",
				dataType:"json",
				success:function(result){
					if(result.b){
						alert("添加成功!");
						closeAdd("Popup");
						$("#addButton").removeAttr("disabled");
						document.location.reload();//页面实现跳转或刷新
					}else{
						alert("添加失败!");
					}
					
				},
				error:function(error){
					$("#addButton").removeAttr("disabled");
					alert("save()保存,发生错误!");
				}
			});
		}

JQuery中$.ajax()方法参数详解

url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。

type:要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和delete也可以使用,但仅部分浏览器支持。

timeout:要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。

async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。 如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。

cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false)。设置为false将不会从浏览器缓存中加载请求信息。

data: 要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后。防止这种自动转换,可以查看processData选项。对象必须为key/value格式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。

dataType:要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。 可用的类型如下:

         xml:返回XML文档,可用JQuery处理。

         html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。

         script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求

                 时(不在同一个域下),所有post请求都将转为get请求。

         json:返回JSON数据。

         jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个

               “?”为正确的函数名,以执行回调函数。

         text:返回纯文本字符串。

beforeSend:要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义

           HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参

           数。

           function(XMLHttpRequest){

               this;  //调用本次ajax请求时传递的options参数

           }

complete:要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。

         参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。

         function(XMLHttpRequest, textStatus){

            this;   //调用本次ajax请求时传递的options参数

         }

success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。

        (1)由服务器返回,并根据dataType参数进行处理后的数据。

        (2)描述状态的字符串。

        function(data, textStatus){

            //data可能是xmlDoc、jsonObj、html、text等等

           this;  //调用本次ajax请求时传递的options参数

error:要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错

      误信息、捕获的错误对象(可选)。

      ajax事件函数如下:

      function(XMLHttpRequest, textStatus, errorThrown){

         //通常情况下textStatus和errorThrown只有其中一个包含信息

         this;  //调用本次ajax请求时传递的options参数

      }

contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认

            为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。

dataFilter:要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。

           提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的

           dataType参数。函数返回的值将由jQuery进一步处理。

           function(data, type){

               //返回处理后的数据

               return data;

           }

global:要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局

       ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。

ifModified:要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。

           服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。

jsonp:要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。

      该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如

      {jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。

username:要求为String类型的参数,用于响应HTTP访问认证请求的用户名。

password:要求为String类型的参数,用于响应HTTP访问认证请求的密码。

processData:要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度

            来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM

            树信息或者其他不希望转换的信息,请设置为false。

scriptCharset:要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时

              才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。

 

案例代码:

$(function(){

   $('#send').click(function(){

        $.ajax({

            type: "GET",

            url: "test.json",

            data: {username:$("#username").val(),content:$("#content").val()},

            dataType: "json",

             success:function(data){

                         $('#resText').empty();  //清空resText里面的所有内容

                        var html = ''; 

                        $.each(data, function(commentIndex, comment){

                              html += '<divclass="comment"><h6>'+ comment['username']

                                        + ':</h6><pclass="para"' + comment['content']

                                        +'</p></div>';

                        });

                        $('#resText').html(html);

                     }

        });

    });

});

 

顺便说一下$.each()函数:

$.each()函数不同于JQuery对象的each()方法,它是一个全局函数,不操作JQuery对象,而是以一个数组或者对象作为第1个参数,以一个回调函数作为第2个参数。回调函数拥有两个参数:第1个为对象的成员或数组的索引,第2个为对应变量或内容。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值