Home Web Front-end JS Tutorial jQuery form serialization example code

jQuery form serialization example code

Jun 21, 2017 pm 04:34 PM
jquery code Example Serialization form

This article mainly introduces the jQuery form serialization example code. Friends who need it can refer to it

No more nonsense, I will post the code directly for everyone. The specific code is as follows Said:


$(function(){
  $('#send').click(function(){
     $.ajax({
       type: "GET",
       url: "test.json",
       data: {username:$("#username").val(), password:$("#password").val()}, // 参数为对象
       dataType: "json",
       success: function(data){
          // code...   
       }
     });
  });
});
$(function(){
  $('#send').click(function(){
    var username = $("#username").val();
    var password = $("#password").val();
    $.ajax({
      type: "GET",
      url: "test.json",
      data: "username"+username+"&password"+password, // 参数为字符串拼接,并用&连接
      dataType: "json",
      success: function(data){
        // code...
      }
    });
  });
});
Copy after login

The above is a regular ajax request code, which lists two transmission formats of data parameters.

In order to facilitate the acquisition of data parameters during ajax requests, jquery defines several quick methods.

1.serialize()

Usage: var data = $("form").serialize();

Return value: The form The content is serialized into a string.

In this way, when submitting form data with ajax, there is no need to list each parameter one by one. Just set the data parameter to $("form").serialize().

The core method is $.param(), which is used to serialize an array or object according to key/value,

var obj = {first:" one",last:"two"};
var str = $.param(obj);
console.log(str); // first=one&last=two

In addition, use serialize One advantage is that it comes with Chinese compilation and processing. Therefore, it is recommended to use serialize.

2.serializeArray()

Usage: var jsonData = $("form").serializeArray();

Return value: Serialize the page form into a JSON structure (key-value pair) object.

For example, [{"name":"lihui", "age":"20"},{...}] gets the data as jsonData[index].name

To sum up : When using ajax to submit form data, the data parameter can be set to $(form).serialize() or $(form).serializeArray(). In addition, it is recommended to refer to w3c for some details.

Finally add a complete example.

html:


<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <form id="demo">
    <input type="text" value="demo1" name="demo1">
    <input type="text" value="demo2" name="demo2">
    <input type="text" value="demo3" name="demo3">
    <input type="submit" value="提交" id="submit">
  </form>
</body>
</html>
Copy after login

JavaScript


##

<script>
  // 别忘了引入jquery !!!
  $(function(){
    $("#submit").click(function(){
    // var data = $("form").serializeArray();
      var data = $("form").serialize();
      $.ajax({
        type:"GET",
        url:"1.php",
        data:data,
        dataType:"json",
        success:function(data){
          console.log(data);
        },
        error:function(xhr,error){
          console.log(error);
        }
      })
    })
  })
</script>
Copy after login

php Reminder : Need to configure the php environment and open the server


<?php 
   echo json_encode($_GET);
 ?>
Copy after login

The above is the detailed content of jQuery form serialization example code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

GE universal remote codes program on any device GE universal remote codes program on any device Mar 02, 2024 pm 01:58 PM

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

How to use Copilot to generate code How to use Copilot to generate code Mar 23, 2024 am 10:41 AM

As a programmer, I get excited about tools that simplify the coding experience. With the help of artificial intelligence tools, we can generate demo code and make necessary modifications as per the requirement. The newly introduced Copilot tool in Visual Studio Code allows us to create AI-generated code with natural language chat interactions. By explaining functionality, we can better understand the meaning of existing code. How to use Copilot to generate code? To get started, we first need to get the latest PowerPlatformTools extension. To achieve this, you need to go to the extension page, search for &quot;PowerPlatformTool&quot; and click the Install button

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension &quot;.a&quot; have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run &quot;.a&quot; files. This article will introduce how to comprehensively install and configure the Linux &quot;.a&quot; file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux &quot;.a&quot; file. What is L

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Apr 17, 2024 pm 02:28 PM

The big model subverts everything, and finally got to the head of this editor. It is also an Agent that was created in just one sentence. Like this, give him an article, and in less than 1 second, fresh title suggestions will come out. Compared to me, this efficiency can only be said to be as fast as lightning and as slow as a sloth... What's even more incredible is that creating this Agent really only takes a few minutes. Prompt belongs to Aunt Jiang: And if you also want to experience this subversive feeling, now, based on the new Wenxin intelligent agent platform launched by Baidu, everyone can create their own intelligent assistant for free. You can use search engines, smart hardware platforms, speech recognition, maps, cars and other Baidu mobile ecological channels to let more people use your creativity! Robin Li himself

Tips for using Laravel form classes: ways to improve efficiency Tips for using Laravel form classes: ways to improve efficiency Mar 11, 2024 pm 12:51 PM

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel

How does Java serialization affect performance? How does Java serialization affect performance? Apr 16, 2024 pm 06:36 PM

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! Jun 08, 2024 pm 09:55 PM

Produced by 51CTO technology stack (WeChat ID: blog51cto) Mistral released its first code model Codestral-22B! What’s crazy about this model is not only that it’s trained on over 80 programming languages, including Swift, etc. that many code models ignore. Their speeds are not exactly the same. It is required to write a "publish/subscribe" system using Go language. The GPT-4o here is being output, and Codestral is handing in the paper so fast that it’s hard to see! Since the model has just been launched, it has not yet been publicly tested. But according to the person in charge of Mistral, Codestral is currently the best-performing open source code model. Friends who are interested in the picture can move to: - Hug the face: https

See all articles