How to manipulate Ajax in the JavaScript jquery library explain _jquery

Source: Internet
Author: User
Tags aop echo date require ssh jquery library advantage


Java software Development, in the background, we can through a variety of frameworks, such as SSH, and so on code encapsulation, to facilitate our Java code writing, for example, Struts,springmvc from the foreground to the action of the process of encapsulation control, This allows us to implement only a few simple configurations, while spring encapsulates the management of various objects, providing an AOP programming approach that greatly facilitates us, while Hibernate and Ibatis encapsulate the JDBC code We do not need to write repetitive and complex JDBC code every time.

At the front desk, for some of the effects of the page, validation, etc., we are all through the JavaScript language, but it is also like our Java code, is the most basic front language, and jquery is the JS code for encapsulation to facilitate the preparation of our front desk code, And it has a very big advantage is to solve the browser compatibility problem, which we use it is very important one of the reasons.

And now in order to meet the needs of users, Ajax (asynchronous Javascript + XML) Asynchronous refresh has played an unparalleled role in the previous AJAX operations, always require us to want the JDBC code to do several necessary steps:
ajax--core XMLHttpRequest objects, and jquery also encapsulates Ajax asynchronous operations, looking at several common ways. $.ajax,$.post, $.get, $.getjson.



$.ajax, this is the most fundamental step in jquery's encapsulation of Ajax, by using this function to complete all the functions of asynchronous communication. In other words, we can use this method to asynchronously refresh the operation. But it has more parameters and may sometimes be troublesome. Take a look at the commonly used parameters:


 var configobj = {  method//Data submission: Get and post
    URL  //Data Submission Path strength async//  support asynchronous Refresh, default is True
    Data  //need to submit DataType//  server returns the type of data, such as Xml,string,json
    success  //Request successful callback function
    error  /////Request failed callback function
  }
 
$.ajax (configobj);//called Through the $.ajax function.



OK, let's look at a practical example and look at an example of an asynchronous deletion:



Java software Development, in the background, we can through a variety of frameworks, such as SSH, and so on code encapsulation, to facilitate our Java code writing, for example, Struts,springmvc from the foreground to the action of the process of encapsulation control, This allows us to implement only a few simple configurations, while spring encapsulates the management of various objects, providing an AOP programming approach that greatly facilitates us, while Hibernate and Ibatis encapsulate the JDBC code We do not need to write repetitive and complex JDBC code every time.
 
Foreground, for some of the effects of the page, validation, etc., we are all done through the JavaScript language, but it is also like our Java code, is the most basic of the most foreground language, And jquery is the JS code encapsulation to facilitate the writing of our front desk code, and it also has a very big advantage is to solve the browser compatibility problem, which is why we use it is very important one of the reasons.
 
and now to meet the needs of users, Ajax (asynchronous Javascript + XML) Asynchronous refresh has played an unparalleled role in the previous AJAX operations, always require us to want the JDBC code to do several necessary steps:
ajax--core XMLHttpRequest objects, and jquery also encapsulates AJAX asynchronous operations, looking at several common ways. $.ajax,$.post, $.get, $.getjson.
 
$.ajax, which is the most fundamental step in jquery's encapsulation of Ajax, by using this function to complete all the functions of asynchronous communication. In other words, we can use this method to asynchronously refresh the operation. But it has more parameters and may sometimes be troublesome. Take a look at the commonly used parameters:      &NBSP


 var configobj = {  method//Data submission: Get and post
    URL  //Data Submission Path strength async//  support asynchronous Refresh, default is True
    Data  //need to submit DataType//  server returns the type of data, such as Xml,string,json
    success  //Request successful callback function
    error  /////Request failed callback function
  }
 
$.ajax (configobj);//called Through the $.ajax function.



OK, let's look at a practical example and look at an example of an asynchronous deletion:


 <span style= "FONT-SIZE:18PX;" >//delete $.ajax ({type: "POST",//Submit as URL: "${pagecontext.request.contextpath}/org 
          /dodelete.action ",//Path data: {" org.id ":" ${org.id} "},//, used in JSON format for transmission Success:function (Result) {//Return data is processed according to the results if (result.success) {$ ("#tipMsg"). Text ("Delete 
              Data Success "); 
            Tree.deleteitem ("${org.id}", true); 
            else {$ ("#tipMsg"). Text ("Delete data failed"); 
} 
          } 
        }); </span> 


$.post, this function is actually a further encapsulation of the $.ajax, reducing the parameters, simplifying the operation, but the scope of the application is smaller. $.post simplifies the way data is submitted and can only be submitted by post. Can only be an asynchronous access server, cannot synchronize access, and cannot do error handling. In satisfying these cases, we can use this function to facilitate our programming, and its main parameters, such as Method,async, are set by default, and we cannot change it. Examples are no longer introduced.
URL: Sends the request address.
Data: Key/value parameter to be sent.
Callback: callback function when sending success.
Type: Returns the content format, XML, HTML, script, JSON, Text,_default.
 
$.get, like $.post, encapsulates the submission data for a Get method and can only be used in a way that solves an asynchronous refresh with the get submit data, and is similar to the one on the top. This is no longer demonstrated here.
 
$.getjson, which is a further encapsulation, that is, the return data type is manipulated for JSON. Inside on three parameters, we need to set, very simple: url,[data],[callback].
 
In fact, the $.ajax method, the other will be used, are the same, in fact, very simple.
 
But here is another problem, the trouble is, if the page data volume is larger, what should I do? In the processing of regular forms, we use the framework Struts2 to automate the acquisition of encapsulation through domain-driven mode, so how do we encapsulate it through Ajax? Here jquery has a plugin, jquery form, by introducing this JS file, we can simulate form form to support STRUTS2 domain-driven mode and carry out automatic data encapsulation. The usage is similar to $.ajax, look at the actual example, write a foreground code to save the user:
 


 <span style= "FONT-SIZE:18PX;" > $ (function () {var options = {Beforesubmit:function () {//processing previously required function $ ("tipmsg"). Text (data is being saved, please 
        Wait a minute ... "); 
      $ ("#insertBtn"). attr ("Disabled", true); Success:function (Result) {//returns the callback function required after success if (result.success) {$ ("#tipMsg"). Text ("mechanism saved into 
                   
                    Work "); 
          Here is a corresponding tree, which will be introduced to,//control of the tree component, add new node var trees = Window.parent.treeFrame.tree; 
        Tree.insertnewchild ("${org.id}", Result.id, Result.name); 
        else {$ (' #tipMsg '). Text ("mechanism save Failed"); 
      //Enable Save button $ ("#insertBtn"). attr ("disabled", false); 
   
    }, Clearform:true}; $ (' #orgForm '). Ajaxform (options); 
Submitted through the Ajaxform method in Jquery.form}); </span> 



So we do not have to do data encapsulation processing, greatly simplifying our AJAX operations such as asynchronous refresh operation. For the Ajax operation in jquery, the feeling of using more, and form forms of processing is very similar, but the implementation of the function is not the same. Learning programming, in fact, is to learn the flow of data processing, how to obtain from the foreground, transfer to the server for the corresponding processing, and then return, the relevant display, the process through a number of technical implementation, the completion of the software development, the feeling is still very interesting.



Simplifying Ajax development with JQuery



Ajax is not a language, it's just a combination of old technologies like JavaScript and XML and DOM, all called asynchronous JavaScript and XML, asynchronous JavaScript and XML, which can be used in pages that don't refresh Under the premise of asynchronous data interaction with the server, if used properly, it can improve the user experience, but also to save bandwidth, reduce server pressure. As a good JavaScript framework, JQuery also offers a number of ways to handle AJAX-related operations.
using Ajax to get asynchronous data



Traditional Ajax general steps are:


    • Create XMLHttpRequest (compatible with various browsers).
    • Sends a XMLHTTPREQUEST request to the server.
    • Monitoring of XMLHttpRequest onreadystatechange events.
    • Determine if the service side responds to completion and the response is normal.
    • Gets the results that Ajax returns from the server.


For example, using Ajax to get the current time on the server, the sample code is as follows:


 
 


The service-side code is:


<?php
 //server is Greenwich Standard Time, which is set to China's time zone
 date_default_timezone_set ("PRC");
 echo Date ("y-m-d h:i:s");
? >


As you can see, with this simple functionality, the code is so verbose, especially when creating XMLHttpRequest, but also with multiple browsers, as well as monitoring XMLHttpRequest onreadystatechange time and returning ReadyState and status, slightly troublesome.



The Ajax method of jquery, if the above code is rewritten as the Ajax method of jquery, the code is as follows:


 
 


As you can see, the Ajax approach to JQuery, the main code is only one line of $ ("#timediv"). Load ("ajax.php"); it's quite simple and absolutely compatible with all the major browsers. As you can see from this example, jQuery greatly simplifies the way Ajax is encoded.
Get or POST?



The load function in the example above is convenient, but we often have to specify whether JQuery is using the Get method or POST method, using the following methods:


  $.get (URL, [data], [callback])
  $.post (URL, [data], [callback], [type])


The use of Get and POST is basically the same, with parameter data being sent to the server, callback as a callback function, type used to specify the type of data returned by the server, such as plain text, XML, JSON, and so on.



Here's a concrete example:


<html>
<head>
<title>jQuery Ajax (get and post)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js?ver=1.4.4"></script>
<script type="text/javascript">
$(document).ready(function() {
//Add event for get button
$("#getbtn").click(function() {
$.get("ajaxpage.php", {username:$("#username").val()}, function(data) {
$("ාajaxdata"). HTML (data); / / fill the data returned by the server into the P tag
};
};
//Add event for post button
$("#postbtn").click(function() {
$.post("ajaxpage.php", {username:$("#username").val()}, function(data) {
$("ාajaxdata"). HTML (data); / / fill the data returned by the server into the P tag
};
};
};
</script>
</head>
<body>
Your big name: < input type = "text" id = "username" / > < br / >
< input type = "button" id = "getbtn" value = "get method" / > < br / >
< input type = "button" id = "postbtn" value = "post method" / >
<p id="ajaxdata"></p>
</body>
</html>


 


The service-side code is:


<?php
 //server is Greenwich Standard Time, which is set to China's time zone
 date_default_timezone_set ("PRC");

 $username = "";
 $ajaxMethod = "";
 
 Judge whether get or POST
 if (isset ($_get["username"])) {
 $username = $_get["username"];
 $ajaxMethod = "Get";
 } else {
 $username = $_post["username"];
 $ajaxMethod = "POST";
 }


echo "Hello,". $username. "And now the time is:". Date ("Y-m-d h:i:s"). ", this data comes from." $ajaxMethod. "Ajax";
?>



As you can see, the JQuery Ajax get method and POST method are still quite handy to use.
controlling Ajax



The Get and POST methods, and the load methods mentioned earlier, are very useful, but sometimes it is too simple, and many times we need more control over the details of Ajax, and JQuery also provides some ways to control the details of Ajax, mainly through $.ajax (Opti ONS) method to implement, see the following code fragment:


<script type= "Text/javascript" >
$ (document). Ready (function () {
 //Add Event
 $ ("#getbtn") for Get button. Click (function () {
 $.ajax ({
  type: "Get",
  URL: "ajaxpage.php",
  data: {username:$ ("#username"). Val ()},
  timeout:3000,
  error:function () {
  alert ("error!");
  },
  success:function (data) {
  // A callback function that adds the returned data to the P tag
  $ ("#ajaxdata"). HTML (data)
 
 ;}); Adds an event
 $ ("#postbtn") to the POST button. Click (function () {
 $.ajax ({
  type: POST),//Ajax submit as
  URL: " Ajaxpage.php ",//Submit page Data
  : {username:$ (" #username "). Val ()},//Data timeout:3000 to submit,
  //timeout setting, in milliseconds
  Error:function () {///Ajax Error
  alert ("error!")
  ,},
  success:function (data) {
  //callback function, add returned to P Label
  $ ("#ajaxdata"). HTML (data);});
 }
); </script>


In the example above, the options item in $.ajax (options) is optional, and not every parameter is set. For some parameters, such as timeout and error are fixed in a project, there is no need to write in each AJAX code, you can use the global AJAX settings provided by JQuery to set the method as follows:


<script type= "Text/javascript" >
$ (document). Ready (function () {
 //Global AJAX settings, this setting will apply to all Ajax methods on this page
 $.ajaxsetup ({
 URL: "ajaxpage.php",//Ajax submission page
 timeout:3000,//timeout setting, unit milliseconds
 error:function () {//Ajax hair
  alert ("error!")
 
 at the time of birth error; Adds an event
 $ ("#getbtn") to the Get button. Click (function () {
 $.ajax {
  type: ' Get ',
  data: {username:$ ("# Username "). Val ()},
  success:function (data) {
  //callback function, add the returned data to the P tag
  $ (" #ajaxdata "). HTML (data);
 });
 });
 
 Adds an event
 $ ("#postbtn") to the POST button. Click (function () {
 $.ajax ({
  type: POST),//Ajax Submit Method
  data: { username:$ ("#username"). Val ()},///To submit data
  Success:function
  //callback function, add returned data to P tag
  $ ("# Ajaxdata "). HTML (data);
  }
 });
 }
; </script>


In the example above, the set of parameters in the global settings, in the entire page will be effective, this feature can greatly reduce the duplication of code.



These are some of the simple ways in which jQuery Ajax is used, and the data returned by the server in the above examples are plain text, and in the case of complex Ajax applications, XML or JSON may be needed.
      


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.