Examples of ajax two-level linkage drop-down effect in javascript

Source: Internet
Author: User
Tags http request json string format trim browser cache

First, let's look at the query ajax parameters.

The data sent to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. View the description of the processData option to disable automatic conversion. It must be in Key/Value format. If it is an array, jQuery automatically corresponds to the same name for different values. For example, {foo: ["bar1", "bar2"]} is converted to '& foo = bar1 & foo = bar2 '.

Example:

The code is as follows: Copy code

$. Ajax ({
Type: "POST ",
Url: "some. php ",
Data: "name = John & location = Boston ",
Success: function (msg ){
Alert ("Data Saved:" + msg );
   }
});

Here, the parameters following data can be written in two forms: one is to write common url parameters, and the other is to write them in a json Array,
The data section in the preceding example can also be written as follows: data: {name: "John", location: "Boston "}. What are the differences between the two statements?
Today, I found a slight difference in the usage of the two in development. First, we use the url to pass the parameter. If the parameter contains the "&" symbol, the parameter may not be received or is incomplete, for example, "data: "name = John & location = Boston ",",
If the name value is "john & smith", this may cause a problem. We can escape it using the encodeURIComponent () method in JS,
However, if you use data: {name: "John", location: "Boston"}, you do not need to escape it. If you escape it, you will receive the escaped string.

First, the method for retrieving the drop-down list from php is as follows:

The code is as follows: Copy code

// Obtain the drop-down box data through ajax
Function getCategory (){
$ Cate_id = isset ($ _ POST ['Cate _ id'])? Trim ($ _ POST ['Cate _ id']): '';
If (! $ Cate_id ){
Echo 'Ajax failed to get data ';
} Else {
$ _ Gcategory_mod = & m ('gcategory ');
$ Category = $ _ gcategory_mod-> find (
Array (
'Fields' => 'Cate _ id,
Cate_name, parent_id ',
'Condition' => 'parent _ id = '. $ cate_id
));
Echo json_encode ($ category );
 }
}

Query based on the selected drop-down box or text box and return the result:

The code is as follows: Copy code

// Ajax query
Function c_search (){
$ Cate1 = isset ($ _ POST ['cate1 '])? Intval ($ _ POST ['cate1 ']): 0;
$ Cate2 = isset ($ _ POST ['cate2'])? Intval ($ _ POST ['cate2']): 0;
$ Cate3 = isset ($ _ POST ['cate3 '])? Intval ($ _ POST ['cate3 ']): 0;
$ Good_name = isset ($ _ POST ['good _ name'])? Trim ($ _ POST ['good _ name']): 0;
// Echo $ good_name; exit;
$ Page = $ this-> _ get_page ();
If ($ cate1! = 0 ){
$ Condition = 'Cate _ id_1 = '. $ cate1;
If ($ cate2! = 0 ){
$ Condition. = 'and cate_id_2 ='. $ cate2;
  }
If ($ cate3! = 0 ){
$ Condition. = 'and cate_id_3 ='. $ cate3;
  }
 }
 
If ($ good_name! = 'Enter the product name ')){
 
$ Condition = 'goods _ name like "% '. $ good_name.' % "';
 }
$ Condition. = 'and if_show = 1 ';
// Print_r ($ condition); exit;
$ _ Gcategory_mod = & m ('gcategory ');
$ Cate1 =$ _ gcategory_mod-> find (array ('fields' => 'Cate _ id, cate_name, parent_id ', 'condition' => 'parent _ id = 0 '));
$ This-> assign ('cate1 ', $ cate1 );
 
 
// Print_r ($ condition); exit;
$ List = $ this-> _ goods_mod-> find (array (
'Fields' => '*',
'Condition' => $ condition,
'Order' => "goods_id desc ",
'Count' => true,
'Limit' => $ page ['limit']
));
 
// Print_r ($ list); exit;
$ Page ['item _ count'] = $ this-> _ goods_mod-> getCount ();
$ This-> _ format_page ($ page );
 
$ This-> assign ('page _ info', $ page );
// Print_r ($ page); exit;
$ This-> assign ('list', $ list );
$ This-> display ('dapei.new.html ');
}
}

Output json format.

The code is as follows: Copy code

<Script type = "text/javascript">
$ (Function (){
$ ("# Cate1"). change (function (){
// Alert ("32 ");
Cate1_id = $ (this). val ();
$. Ajax ({
Url: "../admin/index. php? App = dapei & act = getCategory ",
Type: "post ",
DataType: "json ",
Data: {cate_id: cate1_id },
Success: function (data ){
$ ("# Cate2"). empty ();
$ ("<Option value = '0'> -- select -- </option> ")
. AppendTo ("# cate2 ");
$. Each (data, function (I, item ){
$ ("<Option> </option> ")
. Val (item. cate_id)
. Text (item. cate_name)
. AppendTo ("# cate2 ");
});
   }
});
});
 
$ ("# Cate2"). change (function (){
Cate1_id = $ (this). val ();
$. Ajax ({
Url: "../admin/index. php? App = dapei & act = getCategory ",
Type: "post ",
DataType: "json ",
Data: {cate_id: cate1_id },
Success: function (data ){
$ ("# Cate3"). empty ();
$ ("<Option value = '0'> -- select -- </option> ")
. AppendTo ("# cate3 ");
$. Each (data, function (I, item ){
$ ("<Option> </option> ")
. Val (item. cate_id)
. Text (item. cate_name)
. AppendTo ("# cate3 ");
});
   }
});
});
 
$ ("# C_search"). click (function (){
$. Ajax ({
Url: "../admin/index. php? App = dapei & act = c_search ",
Type: "post ",
DataType: "html ",
Data :{
Cate1: $ ("# cate1"). val (),
Cate2: $ ("# cate2"). val (),
Cate3: $ ("# cate3"). val ()
},
DataType: "html ",
Success: function (data ){
// Alert (data );
$ ("# Dapei_fenye"). empty (). append ($ (data). find ("# dapei_fenye" ).html ());
   }
});
});
 
$ ("# Name_search"). click (function (){
// Alert ("fsad ");
$. Ajax ({
Url: "../admin/index. php? App = dapei & act = c_search ",
Type: "post ",
DataType: "html ",
Data :{
Good_name: $ ("# good_name"). val ()
},
DataType: "html ",
Success: function (data ){
// Alert (data );
$ ("# Dapei_fenye"). empty (). append ($ (data). find ("# dapei_fenye" ).html ());
   }
});
});
})
</Script>

There are still many parameters for ajax. The following is a reference for a table.

Parameter name
Type
Description
Url
String
(Default: current page address) the address of the request sent.
Type
String
(Default: "GET") request method ("POST" or "GET"). The default value is "GET ". Note: Other HTTP request methods, such as PUT and Delete, can also be used, but are only supported by some browsers.
Timeout
Number
Set the request timeout (in milliseconds ). This setting overwrites the global setting.
Async
Boolean
(Default: true) by default, all requests are asynchronous requests. To send a synchronization request, set this option to false. Note: The synchronous request locks the browser. Other operations can be performed only after the request is completed.
BeforeSend
Function
Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header. The XMLHttpRequest object is a unique parameter.
Function (XMLHttpRequest ){
This; // the options for this ajax request
}
Cache
Boolean
(Default: true) new jQuery 1.2 Function. Setting this parameter to false will not load request information from the browser cache.
Complete
Function
Callback function after the request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object, success Information string.
Function (XMLHttpRequest, textStatus ){
This; // the options for this ajax request
}
ContentType
String
(Default: "application/x-www-form-urlencoded") content encoding type when sending information to the server. The default value is applicable to most applications.
Data
Object,
String
The data sent to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. View the description of the processData option to disable automatic conversion. It must be in Key/Value format. If it is an array, jQuery automatically corresponds to the same name for different values. For example, {foo: ["bar1", "bar2"]} is converted to '& foo = bar1 & foo = bar2 '.
DataType
String
Expected data type returned by the server. If this parameter is not specified, jQuery will automatically return responseXML or responseText based on the MIME information of the HTTP package and pass it as a callback function parameter. Available values:
"Xml": returns an XML document, which can be processed by jQuery.
"Html": returns plain text HTML information, including script elements.
"Script": returns plain text JavaScript code. Results are not automatically cached.
"Json": return JSON data.
"Jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function.
Error
Function
(Default: automatically determines (xml or html) This method is called when a request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.
Function (XMLHttpRequest, textStatus, errorThrown ){
// Generally, textStatus and errorThown have only one value.
This; // the options for this ajax request
}
Global
Boolean
(Default: true) whether to trigger a global AJAX event. Setting false does not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax events
IfModified
Boolean
(Default: false) obtain new data only when the server data changes. Use the Last-Modified header information of the HTTP packet to determine.
ProcessData
Boolean
(Default: true) by default, data sent is converted to an object (technically not a string) with the default content type "application/x-www-form-urlencoded ". If you want to send the DOM tree information or other information that does not want to be converted, set it to false.
Success
Function
Callback function after successful request. This method has two parameters: the server returns data and returns the status.
Function (data, textStatus ){
// Data cocould be xmlDoc, jsonObj, html, text, etc...
This; // the options for this ajax request
}

 

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.