jquery uses Ajax to submit a form instance introduction

Source: Internet
Author: User
Tags getscript

The main way to submit form forms using Ajax is Ajaxform () and Ajaxsubmit (), Ajaxform and Ajaxsubmit support a wide range of option parameters that can be provided using a single Options object. The options is just a JavaScript object that contains a collection of properties and values as follows:

Options object's Detailed:

1.) Target
Indicates the element in the page that is updated by the server response. The value of an element may be specified as a jquery selector string, a jquery object, or a DOM element.
Default value: null.

2.) URL
Overrides or specifies the ' action ' property of the form.
Default value: Form's Action property value

3.) type
Overrides or specifies the ' method ' property of the form, ' get ' or ' POST '.
Default value: The form's Method property value (if the default is "get" is not found).

4.) Beforesubmit
A callback function called before the form is submitted, which is usually provided to run the pre-submit logic or validate the form data. If the "Beforesubmit" callback function returns false, then the form will not be submitted. The "Beforesubmit" callback function takes three call parameters: Form data in array form, jquery Form object, and the options object in the incoming ajaxform/ajaxsubmit. The form singular group accepts data in the following ways:
[{name: ' username ', value: ' Jresig '}, {name: ' Password ', value: ' Secret '}]
Default value: null

5.) Success
callback function that is invoked after a form has been successfully submitted. If a "success" callback function is provided, it is invoked when the response is returned from the server. The datatype option value is then determined to return the value of ResponseText or Responsexml.
Default value: null

6.) DataType

The type of response expected from the server. NULL, "XML", "script", or "JSON" one of them. DataType provides a method that provides a way to handle the response of a server. This is directly reflected in the Jquery.httpdata method. The following values are supported:
' XML ': if datatype = = ' xml ', the server response will be treated as XML. Also, if the "success" callback method is specified, the Responsexml value is returned
' JSON ': if datatype = = ' json ', the server response is evaluated and passed to the "success" callback method if it is specified.
' Script ': if datatype = = ' script ', the server response will be evaluated as plain text.
Default value: null (server returns RESPONSETEXT value)

7.) Semantic
Boolean flags that indicate whether data must be submitted in a strictly semantic order. Note: In general, the form has been serialized (or serialized) in a semantic order, except for the type= "image" INPUT element. If your server has strict semantic requirements, and the form contains an INPUT element with a type= "image", you should set the semantic to true.
Default value: False

8.) Resetform
A Boolean flag that indicates whether the form submission succeeds if it is reset.
Default value: null

9.) ClearForm
A Boolean flag that indicates whether the form data is purged if the form submission succeeds.
Default value: null

10. The elements used in the $.ajax options can be used here:

First, create a new login.html page:

The code is as follows Copy Code
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">


<html xmlns= "http://www.w3.org/1999/xhtml" >


<head>


<title>$.ajax () method sends request </title>


<script type= "Text/javascript" src= "Scripts/jquery-1.4.1.js" ></script>


<style type= "Text/css" >


Body


{


font-size:13px;


}


. divframe


{


width:225px;


Border:solid 1px #666;


}


. Divframe. Divtitle


{


padding:5px;


Background-color: #eee;


height:23px;


}


. Divframe. Divtitle span


{


Float:left;


padding:2px;


padding-top:5px;


}


. Divframe. divcontent


{


padding:8px;


Text-align:center;


}


. divframe. divcontent. clsshow


{


font-size:14px;


Line-height:2.0em;


}


. divframe. divcontent. Clsshow. Clserror


{


font-size:13px;


Border:solid 1px #cc3300;


padding:2px;


Display:none;


margin-bottom:5px;


Background-color: #ffe0a3;


}


. txt


{


border: #666 1px solid;


padding:2px;


width:150px;


margin-right:3px;


}


. btn


{


border: #666 1px solid;


padding:2px;


width:50px;


}


</style>


<script type= "Text/javascript" >


$ (function () {


$ ("#txtName"). focus ();//input focuses


$ ("#txtName"). KeyDown (function (event) {


if (Event.which = = "13") {//Enter, move cursor to Password box


$ ("#txtPass"). focus ();


}


});


$ ("#txtPass"). KeyDown (function (event) {


if (Event.which = = "13") {//Enter, submitting form with. Ajax


$ ("#btnLogin"). Trigger ("click");


}


});


$ ("#btnLogin"). Click (function () {//Log on button clicks event


Get user Name


var strtxtname = encodeURI ($ ("#txtName"). Val ());


Get input password


var Strtxtpass = encodeURI ($ ("#txtPass"). Val ());


Start sending data


$.ajax


({//Request Login Processing page


URL: "Login.aspx",//Login Processing page


DataType: "HTML",


Transfer Request data


Data: {txtname:strtxtname, Txtpass:strtxtpass},


Success:function (strvalue) {//Login successful after the data returned


Show status based on return value


if (strvalue = = "true") {//Note is true, not true


$ (". Clsshow"). HTML ("Action prompt, login successful!"). "+ strvalue);


}


else {


$ ("#divError"). Show (). HTML ("User name or password error!"). "+ strvalue);


}


}


})


})


})


</script>


</head>


<body>


<form id= "Frmuserlogin" >


<div class= "Divframe" >


<div class= "Divtitle" >


<span> User Login </span>


</div>


<div class= "Divcontent" >


<div class= "Clsshow" >


<div id= "Diverror" class= "Clserror" >


</div>


<div>


Name: <input id= "txtname" type= "text" class= "TXT"/></div>


<div>


Password: <input id= "Txtpass" type= "password" class= "TXT"/></div>


<div>


<input id= "Btnlogin" type= "button" value= "Login" class= "BTN"/> &nbsp


<input id= "btnreset" type= "reset" value= "Cancel" class= "Btn"/>


</div>


</div>


</div>


</div>


</form>


</body>


</html>


Then, create a new login.aspx to receive and process the data:

The code is as follows Copy Code
<%@ Page language= "C #" autoeventwireup= "true" codebehind= "Login.aspx.cs" inherits= "Jsdemo.login" responseencoding = "gb2312"%>

<%
String strName = System.Web.HttpUtility.UrlDecode (request["txtname"]);
String strpass = System.Web.HttpUtility.UrlDecode (request["Txtpass"]);
BOOL login = false;
if (strName = "admin" && strpass = = "Admin")
{
Login = true;
}
Response.Write (login);
%>

In addition to the above method of jquery Ajax There are many ways, below to give you a simple list

1. Load (URL, [data], [callback]): Loads the remote HTML file code and inserts it into the DOM.

URL (String): The URL address of the requested HTML page.

Data (MAP): (optional parameters) sent to the server's key/value.

Callback (callback): (optional parameter) a callback function that does not need to be success when the request completes.

This method is passed by default using Get method, and is automatically converted to post if the [data] parameter is passed in. In JQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted into the DOM. Syntax is like "URL #some > selector".

This method makes it easy to dynamically load some HTML files, such as forms.

Sample code:

The code is as follows Copy Code
$ (". Ajax.load"). Load ("http://www.cnblogs.com/yeer/archive/2009/06/10/1500682.html. Post",
function (ResponseText, textstatus, XMLHttpRequest) {
this;//here. This point is the current DOM object, that is $ (". Ajax.load") [0]
alert (responsetext);//Request returned content
alert (textstatus);//Request Status: Success,error
alert (XMLHttpRequest);//xmlhttprequest Object
});

The results are displayed here.

Note: Do not know why the URL write absolute path under FF will be wrong, know the trouble to tell. The following get () and post () examples use an absolute path, so you will go wrong under FF and you will not see the results returned. The Get () and post () examples are called across domains, and they are found to be not able to get results, so the run button is removed.

2. Jquery.get (URL, [data], [callback]): Asynchronous request using Get method

Parameters:

URL (String): The URL address where the request is sent.

Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair, is appended to the request URL as querystring.

Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.

This is a simple GET request function to replace the complex $.ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use $.ajax.

Sample code:

The code is as follows Copy Code

$.get ("./ajax.aspx", {Action: "Get", Name: "Lulu"}, function (data, textstatus) {
The returned data can be xmldoc, jsonobj, HTML, text, and so on.
This Here is the option configuration information for the AJAX request, please refer to the following figure
alert (data);
Alert (Textstatus),//Request status: Success,error, and so on.
Of course, the error is not captured here, because the callback function is not run at all when the error
alert (this);
});

Click Send Request:

This in the Jquery.get () callback function points to the option configuration information for the AJAX request:

3. Jquery.post (URL, [data], [callback], [Type]): Asynchronous request using POST method


Parameters:

URL (String): The URL address where the request is sent.

Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair.

Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.

Type (String): (optional) The official description is: type of data to is sent. The type that should actually be requested for the client (Json,xml, etc.)

This is a simple POST request function to replace the complex $.ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use $.ajax.

Sample code:

Ajax.aspx:

The code is as follows Copy Code

Response.ContentType = "Application/json";
Response.Write ("{result: '" + request["Name"] + ", Hello! (This message comes from server) '} '); JQuery code:
$.post ("Ajax.aspx", {Action: "Post", Name: "Lulu"},
function (data, textstatus) {
Data can be xmldoc, jsonobj, HTML, text, and so on.
This This AJAX request option configuration information, please refer to Jquery.get ().
alert (Data.result);
}, "JSON");

Click Submit:

This sets the requested format to "JSON":

If you set the requested format to "JSON", you are not setting the Response back ContentType as: Response.ContentType = "Application/json"; Then you will not be able to capture the returned data.

Note that alert (data.result); With the Accept header "JSON" set, the data returned here is an object that does not need to be converted to an object with eval ().

4. Jquery.getscript (URL, [callback]): Load and execute a JavaScript file with a Get-mode request.

Parameters
URL (String): The JS file address is to be loaded.

Callback (function): (optional) After successfully loading the callback function.

Before the JQuery 1.2 version, Getscript can only invoke the same domain JS file. 1.2, you can invoke JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script by getscript, add the delay function.

This method can be used for example, when only the editor focus () to load the editor required JS file. Here are some sample code:

Load and execute test.js.
JQuery Code:

The code is as follows Copy Code

$.getscript ("Test.js");


--------------------------------------------------------------------------------

Load and execute ajaxevent.js, and then display the information successfully.

JQuery Code:

The code is as follows Copy Code

$.getscript ("Ajaxevent.js", function () {
Alert ("Ajaxevent.js load complete and execution completed.) What's the difference if you click the Get or Post button above? ");
});

After loading, please click on the load request above to see what the difference is.

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.