Jquery ajax的参数格式化
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Jquery ajax的参数格式化,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2201字,纯文字阅读大概需要4分钟。
内容图文
jQuery的ajax会自动将js对象转换为可传递的参数,$.param(jsobj, boolean),但是默认会把对象中数组类型加上[]符号,后台就不怎么好取了
参数boolean为true时不加[],默认为false。
下面是jQuery参数格式化的源代码
假设对象为{a:1,b:[2,3]}
$.ajax中:
// Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); }
使用的$.param格式化(traditional就是第二个参数)
jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior.if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements.if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older// did it), otherwise encode params recursively.for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serializationreturn s.join( "&" ).replace( r20, "+" ); };
调用buildParams( prefix, a[ prefix ], traditional, add )
function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } elseif ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item.for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } }
原文:http://www.cnblogs.com/guangshan/p/4682109.html
内容总结
以上是互联网集市为您收集整理的Jquery ajax的参数格式化全部内容,希望文章能够帮你解决Jquery ajax的参数格式化所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。