Ajax form submission and background processing simple example
Jan 12, 2018 pm 01:26 PMThis article mainly brings you a simple application based on Ajax form submission and background processing. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help 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 example<input type="text" id="txtcode" name="txtcode" datafield="Code" style="width: 200px" />Us 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 from the front desk.
We can define a general method such as the following code
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; }
Here is a simple way to get all the text in the form, and Put it into a data object. 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.
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); //还原按钮 } }); }
The "xxxxx.aspx/Save" here is the ajax processing page, and the other is a webmethod. We have done some work to prevent customers from moving too fast, serving too slowly, and making 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. And there are 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<string, string>. 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<string, string> 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<string, string> can be regarded as a subset of the attribute set of this data class, and the value (value) of this Dictionary<string, string> 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, I will post the core code
##
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); }
[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; }
JQuery creates an AJAX form submission example for PHP_jquery
Using Vue.js in Laravel to implement Ajax form verification example
Use Session token in php to prevent repeated submission of Ajax forms
The above is the detailed content of Ajax form submission and background processing simple example. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Discuz background login problem solution revealed

The operation process of WIN10 service host occupying too much CPU

How to solve the 403 error encountered by jQuery AJAX request

How to solve jQuery AJAX request 403 error

Are you worried about WordPress backend garbled code? Try these solutions

How to get variables from PHP method using Ajax?

Learn how to handle special characters and convert single quotes in PHP

Discuz background login failed? Teach you how to solve it easily!
