Ajax various implementation methods compare _ajax

Source: Internet
Author: User
Tags call back script tag sha1

Ajax technology after so many years of development, there are some frameworks or class libraries to simplify development work, different framework class libraries are used in a variety of ways. Now, looking back at these technologies and looking at these framework libraries, we can feel the technology evolving and Ajax development is getting easier.

This article collects some representative Ajax development methods on the ASP.net platform, and I will use the actual sample code to demonstrate how to use them, so that you can feel the evolution of Ajax, and also want to introduce some excellent AJAX development methods to you.

To easily introduce these Ajax development methods, I divide them into four-generation technologies.
Note: It is my personal opinion to divide Ajax technology by generation, just to distinguish them better.
In addition, some of the original Ajax development methods that do not take advantage of any framework class libraries will not be discussed in this article.
First generation technology: Generating client proxy script call server
This kind of technology shows the main design ideas of the first generation AJAX framework: The proxy script is generated for the client at the server side, then the server is invoked by these proxy scripts, and the caller does not have to know how the entire call process is implemented, and the invocation style at the client is essentially similar to that of the server-side code.

The representative of this kind of technology has: asp.net AJAX, ajaxpro two service-side framework.
I'll use the ASP.net AJAX framework below to demonstrate how to do AJAX development.

First, we can create a WebService service:

[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
To allow the use of ASP.net AJAX to invoke this Web service from a script, uncomment the downlink. 
[System.Web.Script.Services.ScriptService] public
class WebService1:System.Web.Services.WebService {

    [WebMethod] public
    int Add (int a, int b)
        a + b;
<asp:scriptmanager id= "ScriptManager1" runat= "Server" >
        <asp:servicereference Path= "/webservice1.asmx" inlinescript= "true"/>

Description: The inlinescript= "true" setting is not required, just to let us see what code the ScriptManager generates.

As you can see from the screenshot, in addition to the introduction of the two necessary Ajax client class libraries, the client generates proxy scripts for WebService1.

With this code, we can invoke the service side with the following JavaScript code:

function Call_add () {
    webservice1.add (1,2, showresult);
function Showresult (Result) {
    document.getElementById (' output '). Value = result;

The previous example is too simple, let's take a more complex example, or start with a from server, and define a parameter type first:

public class Customer
    string Name {get; set;}
    public int Age {get; set;}
    public string Address {get; set;}
    public string Tel {get; set;}
    public string Email {get; set;}
Webserice code:
[WebMethod] public
string Addcustomer (Customer customer)
    if (customer = null) Return
        ' customer is null. '

    Simply returns an XML string.
    //Tell the client what data the server received. Return
    xmlhelper.xmlserialize (Customer, Encoding.UTF8);

Still borrow the previous ScriptManager settings to see the JavaScript calling code:

function Call_addcustomer () {
    var customer = {Name:document.getElementById ("txtname"). Value, age 
                    : document.getElementById ("Txtage"). Value, 
                    Address:document.getElementById ("txtaddress"). Value, 
                    Tel: document.getElementById ("Txttel"). Value, 
                    Email:document.getElementById ("Txtemail"). value};
    Webservice1.addcustomer (Customer, showresult);

Basically, it is similar to the way the server is encoded, first creating a customer object and then passing it to the calling method.

Prior to that era (2006), the original AJAX implementation was very complex, and this approach made the client code style look similar to the service side, which is really a great design idea. However, the technology has been improving, and now, in the 2013, when we look back at this approach, we will find that it does exist in some imperfections, so that fewer people are now using this method, and this technology is being eliminated.

In fact, we can think from another angle: If this method is really good, it will not be eliminated, it is because there is a better way to appear, it will be eliminated fate.
The improvement direction of new technology
The AJAX approach described earlier would allow the client's calling code to be basically consistent with the server's code style, and why the seemingly perfect approach was eliminated.

Let me analyze the drawbacks of this development approach:
1. Front-end code is not independent enough, you must add a reference to the page before invoking the service side, which is actually a strong coupling.
2. A better front end frame is available to reduce the amount of code that calls the parameters.

Continue reading this article, and you will find that the new approach I'm about to follow is working toward addressing these flaws, which also point to the direction of improvement in the new technology.

Because the front end is calling the server, the proxy script needs to be generated beforehand, which hinders the encapsulation of the front-end code. You can imagine that if the client needs a "Get current user information" feature that must be implemented by the server, then we can only expect the server to generate the proxy class for the client to invoke this functionality. But this feature is so useful that it needs to be used in many places, and you will want to extract it into a common file.

Unfortunately: even if you extract the calling code into a common public.js file, each page cannot invoke the "Get Current user information" feature after referencing Public.js, because the proxy script does not necessarily exist, and the code in the Public.js does not work. What to do.

A: For each page referencing Public.js, add ScriptManager to quote that service.

The higher the functionality of sharing, the higher the repetition of this reference code is found.
Simply put, this method will webservice, aspx page, JS code coupled together.
Because of coupling, the more you use the more trouble you find.

This generation of proxy script development method can make the front-end code and back-end code consistent style, however, the front-end and back end is not the same development language, they have to pay attention to the direction is different. Especially when the more excellent front-end frame appears, this method not only makes the back end and the front-end coupled together, but also restricts the development of front-end technology, ultimately can only be abandoned fate.

Now, remember what code we wrote to submit a customer message:

var customer = {Name:document.getElementById ("txtname"). Value, 
                Age:document.getElementById ("Txtage"). Value, 
                Address:document.getElementById ("txtaddress"). Value, 
                Tel:document.getElementById ("Txttel"). Value, 
                Email:document.getElementById ("Txtemail"). Value};

When I introduce the fourth generation technology, you will find that they are gone.
Second-generation technology: jquery calls WebService directly
Random jquery front-end class library of the popular, another new development method is also beginning to become popular.

HTTP invocation is a very simple and transparent technique, as long as you specify a URL to construct a request body, the front-end proxy scripting method encapsulates the process because its encapsulation creates coupling and limits the development of the front-end. The new Ajax technology can only break through this limitation, discard these proxy scripts, and call back-end code directly.

The following example code is based on the previous example, except that the proxy class is not required and is now called directly to the server.

Since the backend service code has not changed, I will no longer post them, and the page does not need to add any references, we will look directly at the front-end code good:

$.ajax ({
    type: "POST", url: "/webservice1.asmx/add", 
    contentType: "Application/json",
    data: "{a:1, B:2}" ,
    dataType: ' json ',
    success:function (Result) {                    
        $ ("#output"). Val (RESULT.D);

This code can also invoke the server-side Add method.

Because the server uses the JSON data format, it is necessary to specify a number of request headers on the client, which were previously done by the proxy script. Although the code is a little bit more, but the coupling is gone, it is easier to extract some common code.

In fact, if you keep calling WebService in this way, jquery provides the ability to set default parameters, and we can use this feature to reduce the amount of code.

Let's take a look at the front-end calling code for the complex parameter type in front of you:

var customer = {Name: $ ("#txtName"). Val (), Age 
                : $ ("#txtAge"). Val (), Address 
                : $ ("#txtAddress"). Val (), 
                Tel : $ ("#txtTel"). Val (), 
                Email: $ ("#txtEmail"). Val ()};
var jsonstirng = $.tojson ({customer:  customer});

$.ajax ({
    type: "POST", url: "/webservice1.asmx/addcustomer", 
    contentType: "Application/json",
    data: JSONSTIRNG,
    dataType: ' json ',
    success:function (Result) {
        $ ("#output"). Val (RESULT.D);

The main code is still the same, concentrating on getting the call arguments, but going to the JSON format.

Once again: Don't stare at it. To specify a large number of jquery parameters, they can be resolved by setting the default value.
I don't want them to go away now because there are better ways to keep them.

Note: This method can be used not only to invoke WebService, but also to WCF (BasicHttpBinding), after all they use the HTTP protocol. However, WCF also has a bunch of annoying configurations to set up, but this is not a problem with jquery, which is a flaw in the server-side framework.
The third generation technology: a simpler data format
We saw that we could use jquery to invoke WebService, but the JSON conversion process felt a bit redundant, and the browser's submission did not have this transformation step. Sometimes I see some guys still stitching up JSON strings in JavaScript, so I'm very disgusted, so this example code doesn't smear that way, I'm using a JSON plugin.

The third generation technology solves the problem that the input and output must use JSON, and solves the limitation of post.

Since this change changed the format of the data, the server has also changed, and the new framework addresses these issues, such as the ASP.net MVC Framework, MYMVC Framework supports this development approach.

Take a look at the service-side code now:

public int Add (int a, int b)
    a + b;

public string Addcustomer (customer customer)
    //simply returns an XML string.
    //Tell the client what data the server received. Return
    xmlhelper.xmlserialize (Customer, Encoding.UTF8);

Note: This AJAX technology does not have any coupling with the client, as long as you know a URL can be invoked. Look at the client code:

$.ajax ({
    type: "POST", url: "/ajaxdemo/add.cspx", 
    data: {a:1, b:2},
    success:function (Result) {                    
        $ ("# Output "). val (result);

The second call to
var customer = {Name: $ ("#txtName"). Val (), Age 
                : $ ("#txtAge"). Val (), Address 
                : $ ("#txtAddress"). Val (), 
                Tel: $ ("#txtTel"). Val (), 
                Email: $ ("#txtEmail"). Val ()};

$.ajax ({
    type: "POST", url: "/ajaxdemo/addcustomer.cspx", 
    success:function (Result) {
        $ ("#output"). Val (result);

Note: type: "POST" is not required, you can also change them to get method submission.

If you use Fiddler to view the requested content at this point, you will find that the requested data is in a Key=value&key=vlaue format, in the same way as the browser. Because there is no JSON data format limitations, the parameters are now simple.

Now look at the code above, where the main amount of code is.
is not the block that gets the call argument.
Keep reading this and I'm going to make it disappear.
Fourth generation technology: direct submission of forms
Let's take a look at the sample form:

New Customer Information Name:

Before submitting this form in three ways, let's look at a simpler way to submit: (function () {

You can change the form to an asynchronous commit by simply following this call. ("#form1"). Ajaxform ({success:function (Result) {$ (' #output '). Val (result);}); });

I even posted the script tag to show this method more clearly.
If you've ever used jquery you should be able to see that the real code is just the Ajaxform call.
Description: Ajaxform is a feature provided by the Jquery.form plug-in.

The server-side code continues to use the code from the previous example, so it is not posted.

Comparing the previous implementations of Ajax, you can say which method is easiest.

Are you interested in the fourth generation of Ajax technology?
I've also designed a sample of three different scenarios to make you feel strong and simple, so read on.
Submission of multiple submit buttons (implemented with Jquery.form)
The relevant front-end code is as follows:


Output: (function () {("#form1"). Ajaxform (function (Result) {$ (' #output '). Val (result);};});

Service-Side code:

public class Ajaxtestautoaction
public string Base64 (string input)
return convert.tobase64string (Input) (Encoding.Default.GetBytes);

public string Md5 (string input)
    byte[] bb = Encoding.Default.GetBytes (input);
    Byte[] MD5 = (new MD5CryptoServiceProvider ()). ComputeHash (BB);
    Return bitconverter.tostring (MD5). Replace ("-", String. Empty);

public string Sha1 (string input)
    byte[] bb = Encoding.Default.GetBytes (input);
    Byte[] SHA1 = (new SHA1CryptoServiceProvider ()). ComputeHash (BB);
    Return Bitconverter.tostring (SHA1). Replace ("-", String. Empty);

The code is still clear:
1. The service-side defines three methods, corresponding to three submit buttons.
2. Front end or just call one ajaxform to solve all problems.

This approach is implemented by the front-end JQuery, Jquery.form, and server-side MYMVC frameworks. Imagine how much code it would take to take advantage of the other three methods.
Submission of a batch input control (implemented with Jquery.form)
To show another example of reality, a batch input interface is submitted.

The page form code is as follows:

Bulk new customer information Name age address Tel Email

Note: The entire row of data is valid only if the Name,age,tel is valid.

JavaScript code: (function () {("#form1"). Ajaxform ({success:function (Result) {$ (' #output '). Val (result);});}; The service-side code is as follows: public class Batchsubmitcustomer {public string[] ' Name {get; set;} ' public string[] ' age ' {get; set;} Public St Ring[] Address {get; set;} public string[] Tel {get; set;} public string[] Email {get; set;}} [Action] public string Batchaddcustomer (Batchsubmitcustomer input) {List List = new List (), for (int i = 0; I

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.