The use of various Ajax methods is more detailed _ajax related

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

Reading Table of Contents

Begin

First generation technology: Generating client proxy script call server

The improvement direction of new technology

Second-generation technology: jquery calls WebService directly

The third generation technology: a simpler data format

Fourth generation technology: direct submission of forms

Submission of multiple submit buttons (implemented with Jquery.form)

Submission of a batch input control (implemented with Jquery.form)

Submit a complex form (implemented with Jquery.form)

Comparison and summarization of various methods of AJAX development

RELATED LINKS

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)
  {return
    a + b;
  }

This code is a common webservice code, but note that the definition of the class adds a ScriptService modification feature.

Next, we need to generate the client's proxy script for it in an ASPX page, using ScriptManager:

<asp:scriptmanager id= "ScriptManager1" runat= "Server" >
  <Services>
    <asp:servicereference Path= "/webservice1.asmx" inlinescript= "true"/>
  </Services>
</asp:ScriptManager>

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
{public
  string Name {get; set;}
  public int Age {get; set;}
  public string Address {get; set;}
  public string Tel {get; set;}
  public string Email {get; set;}
}

Code for Webserice:

[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, now, in 2013, when we revisit this method, we will find that it does exist some imperfections, so that there are few people use this method now, this technology has been 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 service-side code style, and why would a seemingly perfect approach be 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, do you 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 appearance, this kind of rear end package front End method not only lets the rear end and the front-end coupling together, but also limits the front-end technology development, finally can only be abandoned destiny!

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:

[Action]
public int Add (int a, int b)
{return
  a + b;
}
[Action]
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", 
  Data:customer,
  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 is the main amount of code?

Is it 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:

<form id= "Form1" action= "/ajaxdemo/addcustomer.cspx" method= "POST" >
  <p><b> Add customer information </b> </p>
  <span>name: </span><input type= "text" name= "Name" value= "abc"/><br/>
  <span>age: </span><input type= "text" name= "Age" value= "/><br/>" <span>address
  : </span><input type= "text" name= "Address" value= "Wuhan"/><br/>
  <span>Tel:</span> <input type= "text" name= "Tel" value= "12345678"/><br/>
  : <span>email Type= "text" name= "Email" value= "test@163.com"/><br/> <br/> <input "type="
  submit "Name=" Btnaddcustomer "value=" Save customer information/>
</form>

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

<script type= "Text/javascript" >
$ (function () {
  //Only the following call is required to change the form to asynchronous submission!)
  $ ("#form1"). Ajaxform ({
    success:function (Result) {
      $ (' #output '). Val (result);
}}); </script>

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.

Compared to the previous implementations of Ajax, which method do you say is the simplest?

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)

You think the previous example is too simple, right?

It may be said that if there are multiple submit buttons, this method is not appropriate, I would like to respond to each button, to specify a different URL for them!

Is that so? Look at the example below.

The relevant front-end code is as follows:

<form id= "Form1" action= "/ajaxtestautoaction/submit.cspx" method= "POST" >
  <p><span>input: </span>
    <input type= "text" name= "input" style= "width:300px" value= "Fish Li"/></p>
  ><span>Output:</span>
    <input type= "text" id= "Output" style= "width:300px" readonly= "ReadOnly" /></p>
  <input type= "Submit" Name= "Base64" value= "Convert to Base64 code"/> <input type=
  "Submit" name = "MD5" value= "compute MD5"/>
  <input type= "Submit" Name= "SHA1" value= "calculation sha1"/>
</form>

< Script type= "Text/javascript" >
$ (function () {  
  $ ("#form1"). Ajaxform (function (Result) {
    $ (# Output "). val (result);
  }
); </script>

Service-Side code:

public class ajaxtestautoaction
{
  [Action] public
  string Base64 (String input)
  {
    return Convert.tobase64string (Encoding.Default.GetBytes (input));
  }

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

  [Action]
  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:

JavaScript code:

<script type= "Text/javascript" >
$ (function () {
  
  $ ("#form1"). Ajaxform ({
    success:function (Result) {
      $ ("#output"). Val (result);}});

The service-side code is as follows:

This example of all the code is so much, nonsense do not want to say more, you go to the other way to think how much code you need!

Submit a complex form (implemented with Jquery.form)
The preceding example is a direct submit form, without the process of validating the form, and with a TextBox control as the main, and a complex form example.

The page form code is as follows:

JavaScript code:

<script type= "Text/javascript" >
$ (function () {
  
  $ ("#form1"). Ajaxform ({
    beforesubmit: Validateform,
    success:function (Result) {
      $ (' #output '). Val (result);
    }
  );

  function Validateform (FormData, Jqform, options) { 
    if (jqForm.context.ProductName.value.length = = 0) {
      alert ( "The commodity name cannot be empty. ");
      $ (jqForm.context.ProductName). focus ();
      return false;
    }
    return true;
  }
});

</script>

Service-Side code:

[Action]
public string addproduct (product product)
{
  //simply returns an XML string.
  //Tell the client what data the server received. Return
  xmlhelper.xmlserialize (product, Encoding.UTF8);

Comparison and summarization of various methods of AJAX development

After looking at these examples, let's review the evolutionary process of these Ajax methods:

1. asp.net Ajax as the representative of the "Generate client proxy script invoke Server" technology, in order to wrap the complex process of the original Ajax, the server generated a proxy script for the client, the package after the client in the mode of invocation and service-side basically consistent, it seems to simplify a lot, and reduce the development threshold , however, its advantage is that it is its biggest drawback: the service end of the client-side thing, it completely did not think the client technology is also progressing! When the better front-end technology appears, its ending can only be eliminated.

2. "JQuery Direct call WebService" can be seen as the first generation of technology improvements, it discards the server Generation Agent script function, directly on the client to prepare the server required data format, with the help of jquery internal XMLHttpRequest encapsulation, can also be easily invoked on the server side. This approach solves the coupling of clients, services, and pages, but the data format is limited by the serialization method, which makes it strange. This strange feeling is in fact inconvenient performance.

3. To make the front end easier to invoke the server, the server-side framework can only be changed, the ASP.net MVC framework and the MYMVC framework support simpler data formats, and without that extra asmx file, the class library can be used directly to respond to client requests. The most important feature of this type of technology is that the server can be invoked with a simpler data format. Because of the simplification of data format, the opportunity was left for further improvement.

4. Because the server does not require serialized data formats, and front-end technology is still progressing, finally the Jquery.form plug-in allows us to not need to focus on the collection process of form data, it can simulate the submission behavior of the browser, correctly identify the "successful control" and submit them to the service side, As a result, the code is reduced to the maximum, making it easier to develop the AJAX process.

The previous examples of Jquery.form have also shown that no matter what the form is, it always requires only one call.

And it also makes the call to jquery a very good encapsulation, so I think this is the most easy to use the Ajax development method.

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.