Home Web Front-end JS Tutorial A simple application based on Ajax form submission and background processing

A simple application based on Ajax form submission and background processing

May 23, 2018 pm 02:32 PM
ajax Backstage submit

Below I will bring you a simple application based on Ajax form submission and background processing. Let me share it with you now and give it as a reference for everyone.

First of all, let’s talk about form submission. To submit the form, you must first collect the form data (as for verification, I won’t talk about it. I’ll leave it for next time). With jquery, you can get the html. The value is still as simple as $("xxid").val() and so on, but if a form collects a lot of data, and there are many forms like this, it will definitely be troublesome to use this method, and it is easy to make mistakes in recording. Therefore, we can simply define a collection rule. For example, we can mark the data form control that is to be sent back to the server, and then retrieve the marked data together.

Let’s take the simplest stylistic input as an exampleUs Add a "datafield" attribute, and the stored value is the attribute name of the corresponding server-related class. With this mark, it will be easier to retrieve data at the front desk.

We can define a general method such as the following code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

getFormData: function(formid) {   

    var data = {};

 

    //获取TEXT文件内容

    $("#" + formid + " input[type=text]").each(function(i, o) {

      var jo = $(o);

      if (jo.attr("datafield")) {

        var str = jo.val();

        str = str.replace(" ", "");

        if (str !== "") {         

          data[jo.attr("datafield")] = jo.val();

        }

      }

    });

    return data;

}

Copy after login

This is a simple way to get all the text in the form and put it into a data object. As for I won’t go into details about how to get the values ​​of other form controls, the principles are similar.

The next step is to send the data to the server. I will directly use ajax with jquery here.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

var save = function(sender) {    

      $(sender).prop("disabled", true); //禁用按钮,防止重复发送

      var data = getFormData("form1");

      var jsonobj = { jsondata: data };

      var textdata = JSON.stringify(jsonobj);

      $.ajax({

        type: "POST",

        contentType: "application/json; charset=utf-8",

        url: "xxxxx.aspx/Save",

        dataType: "json",

        data: textdata,

        success: function(msg) {

          if (msg.d == "1") {

            document.form1.reset();

            alert("保存成功!");          

          }

          else if (msg.d == "0") {

            alert("保存失败!");

          }

        },

        complete: function(jqXHR, textStatus) {

          $(sender).prop("disabled", false); //还原按钮

        }

      });

    }

Copy after login

The "xxxxx.aspx/Save" here is the ajax processing page, and the other is a webmethod. We have done some processing to prevent customers from being too fast, service processing being too slow, and repeated clicks.

Such a form data collection and return to the server is completed. The JSON.stringify method of json2.js is used here to uniformly convert objects into json characters. The advantage is that you don’t have to consider the format of json to spell the json string yourself. It is simple and clean.

Then the client has collected the data, and the server should process the data. The key of the data we come from the front desk (json key) cannot all include all attributes of a certain data class. There are also many data classes, and only the server knows which class it is. So here we need to write a helper conversion class. There is another problem here. There may be many data classes. Do I have to write a method for each class? Isn’t that a pitfall? So we analyze the data format transmitted from the client to the server. It is a set of key-value pairs and does not repeat. It is equivalent to a Dictionary. There are many kinds of background classes, so at least we can Once an incoming parameter is determined, the relevant class will be passed out. Related classes? Which category it is can only be known by looking at the specific background collection method. So, let’s sort out our thoughts. Now we have a Dictionary that needs to be turned into a data class. What exactly is a data class and what are its attributes? I can’t figure it out, but the key (key) of this Dictionary can be regarded as a subset of the attribute set of this data class, and the value (value) of this Dictionary is the value of this data class attribute. A subset of toString(). That would be easier to handle. How to get the attribute set? reflection. Which of these categories are there? Regardless, generics solve it.

After talking about so much, post the core code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

public static T1 UpdateObjectByDic<T1>(T1 scrobj, IDictionary<string, string> sourceobject, bool ignoreCase)

     where T1 : new()

    {

      T1 result = scrobj;

      PropertyInfo[] pifresults = typeof(T1).GetProperties();

      foreach (var dic in sourceobject)

      {

        foreach (PropertyInfo pifresult in pifresults)

        {

          if (string.Compare(dic.Key, pifresult.Name, ignoreCase) == 0)

          {

           pifresult.SetValue(result, ChangeType(dic.Value, pifresult.PropertyType), null);

            break;

          }

        }

      }

      return result;

    }

 

    public static Object ChangeType(object value, Type targetType)

    {

      Type convertType = targetType;

      if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))

      {

        NullableConverter nullableConverter = new NullableConverter(targetType);

        convertType = nullableConverter.UnderlyingType;

 

      }

      return Convert.ChangeType(value, convertType);

    }

Copy after login

My T1 scrobj here is to make updates together. If a form is added, it is passed A new object comes in. If the order is updated, the original form data is passed in. By the way, here is the ChangeType method. Others are that some attributes in the data class are nullable (int? DateTime?, etc.). The traditional Convert.ChangeType will have exceptions, so I simply changed it. ignoreCase is the attribute (the value corresponding to the datafield in the front desk) Check whether it handles upper and lower case (usually regardless of case, if you want to handle case, I believe you will be drowned by the front desk's saliva).

This completes the background data processing core, and the calling part of the code is also posted

1

2

3

4

5

6

7

8

9

10

11

[WebMethod(EnableSession = true)]

    public static string Save(Dictionary<string, string> jsondata)

    {

      string result = "0";

      Model.Project pro = ConvertHandle.UpdateObjectByDic< Model.Project>(jsondata,new Model.Project,true);     

      pro.CreatorID = BLL.Sys_User.GetCurUser().ID.ToString();

      pro.CreatorName = BLL.Sys_User.GetCurUser().Name;   

      prohandle.Insert(pro);

      result = "1";

      return result;

    }

Copy after login

Here is the core usage of the background specific processing method call, prohandle.Insert(pro) saves the class into the database , pro.CreatorID, pro.CreatorName are some other information about the project, which I won’t go into. At this point, the front-end data collection and background processing of a form are all finished except for the saving part, haha.

Finally, this is just a simple application. Like the front-end collection I mentioned, many front-end js frameworks have already been developed, and the considerations are much more comprehensive than mine. For background processing, this is Based on my simple collection at the front desk, many third-party frameworks have complete systems, but what I am talking about here is just a simple idea. When you don’t have so many controls at the moment, can you easily follow this path? accomplish. Of course, I strongly recommend not to reinvent the wheel, but you must understand the core function and principle of the wheel.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Ajax Get data by city name

MVC meets ajax form validation after bootstrap

AJAX request queue implementation

The above is the detailed content of A simple application based on Ajax form submission and background processing. 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)

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

Are you worried about WordPress backend garbled code? Try these solutions Are you worried about WordPress backend garbled code? Try these solutions Mar 05, 2024 pm 09:27 PM

Are you worried about WordPress backend garbled code? Try these solutions, specific code examples are required. With the widespread application of WordPress in website construction, many users may encounter the problem of garbled code in the WordPress backend. This kind of problem will cause the background management interface to display garbled characters, causing great trouble to users. This article will introduce some common solutions to help users solve the trouble of garbled characters in the WordPress backend. Modify the wp-config.php file and open wp-config.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

MySQL transaction processing: the difference between automatic submission and manual submission MySQL transaction processing: the difference between automatic submission and manual submission Mar 16, 2024 am 11:33 AM

MySQL transaction processing: the difference between automatic submission and manual submission. In the MySQL database, a transaction is a set of SQL statements. Either all executions are successful or all executions fail, ensuring the consistency and integrity of the data. In MySQL, transactions can be divided into automatic submission and manual submission. The difference lies in the timing of transaction submission and the scope of control over the transaction. The following will introduce the difference between automatic submission and manual submission in detail, and give specific code examples to illustrate. 1. Automatically submit in MySQL, if it is not displayed

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

See all articles