


Detailed explanation of data parameter type examples of JQuery.Ajax()_jquery
Suppose there is such a form now, which is used to add elements.
<form id='addForm' action='UserAdd.action' type='post'> <label for='uname'>用户名</label>:<input type='text' name='uname' id='uname'><br> <label for='mobileIpt'>手机号:</label><input type='text' name='mobileIpt' id='mobileIpt'><br> <label for='birthday'>生日:</label><input type='text' name='birthday'><br> <input type='button' value='提交' onclick='addUser()'> </form>
We don’t want to use form submit to add this element, we want to use ajax to submit.
This is how we implemented it before:
function addUser(){ var user = { uname:$("#uname").val(), mobileIpt:$("#mobileIpt").val(), birthday:$("#birthday").val() }; $.ajax({ url:'UserAdd.action', data:user, type:'post', dataType:'text', success:function(msg){ if(msg=='1'){ console.log('添加成功'); }else{ console.log('添加失败') } } }) }
There is nothing wrong with this, but it is too troublesome to get the values of form elements.... There are only three items here, and it will be useless if there are many items....
Until one day, I discovered jquery’s serializeArray method
Serialized table elements (similar to '.serialize()' method) return JSON data structure data.
Note that this method returns a JSON object rather than a JSON string. You need to use a plug-in or third-party library for stringification operations.
The returned JSON object consists of an array of objects, each of which contains one or two name-value pairs - the name parameter and the value parameter (if value is not empty).
Let’s give it a try
$('#addForm').serializeArray(); //返回数据结构,是json数组,每个对像分别name和value为key,代表这个表单元素的name和value [ {"name":"uname","value":""}, {"name":"mobileIpt","value":""}, {"name":"birthday","value":""} ]
This seems to be useless
Let’s use the JQuery.param() method to handle it:
var arr = $('#addForm').serializeArray(); $.param(arr); "uname=alice&mobileIpt=110&birthday=1983-05-12"
Hey, now it meets our needs. Although it is not of json type, it can at least be uploaded as data.
Here we can directly fill in the json array in the ajax data, and call $.param() inside jquery to process it.
Let’s take a look at the description of the jquery.param() method:
返回值:StringjQuery.param(obj,[traditional]) 将表单元素数组或者对象序列化。 参数 obj,[traditional] 数组或jQuery对象会按照name/value对进行序列化,普通对象按照key/value对进行序列化。 traditional:是否使用传统的方式浅层序列化。 demo: $.param({uanme:'vic',mobileIpt:'110',birthday:'2013-11-11'}); "uanme=vic&mobileIpt=110&birthday=2013-11-11"
Looking at the description, it seems that it has nothing to do with us. Let’s change it to a json array
$.param([{uanme:'vic'},{mobileIpt:'110'},{birthday:'2013-11-11'}]); "undefined=&undefined=&undefined="
Is this conversion unsuccessful? Why can the data in our form be successfully converted into url parameters? Let’s take a look at the jquery source code
//在ajax()方法中,对json类型的数据进行了$.param()处理 if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } //param方法中 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 ); } }
Now you understand, if it is json data, then loop one by one and only take their name attribute and value attribute to splice the string.
If it is a normal object, loop the properties of the object and then concatenate the strings.
Summary:
So, what this article is going to say is that in jquery’s ajax function, 3 types of data can be passed in
1. Text: "uname=alice&mobileIpt=110&birthday=1983-05-12"
2.json object: {uanme:'vic',mobileIpt:'110',birthday:'2013-11-11'}
3.json array:
[ {"name":"uname","value":"alice"}, {"name":"mobileIpt","value":"110"}, {"name":"birthday","value":"2012-11-11"} ]
So, we can get the form and submit it with one click, which is very convenient.
Supplement:
In fact, to extract form data, you only need to use the serialize() method to directly obtain "uname=alice&mobileIpt=110&birthday=1983-05-12".
ps: Summary of usage of data parameter of ajax method in jquery
$.ajax({ type: post, url: some.php, data: name=john&location=boston, //第一种方式传参 // data: {name:john,location:boston} //第二种方式传参 // data: {foo:[bar1, bar2]} 转换为 '&foo=bar1&foo=bar2' /* 第一种我们用url传参,参数里面如果加带&这个符号地话,可能参数接收不到或不完整, 如“ data: name=john&location=boston,” 如果name地值是john&smith这样写可能就会有问题, 我们可以用js里面地encodeuricomponent()方法进行转义, 但如果用data: {name:john,location:boston}这种方式写地话就不需要进行转义, 如果转义地话,接收地将是转义后地字符串 */ success: function(msg){ alert( data saved: + msg ); } });

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools