JQuery Ajax calls Aspx. Net WebService

Source: Internet
Author: User

Here I will call jQuery Ajax to Aspx. several common methods of Net WebService have been sorted out and provided to bloggers who are looking for such content. They hope to help jQuery learners and directly copy and run the code.

 

Ws. aspx 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 id = "Head1" runat = "server">
<Title> </title>

<Script src = "jquery. js" type = "text/javascript"> </script>

<Style type = "text/css">
. Hover
{
Cursor: pointer;/* Small hand */
Background: # ffc;/* background */
}
. Button
{
Width: 150px;
Float: left;
Text-align: center;
Margin: 10px;
Padding: 10px;
Border: 1px solid #888;
}
# Dictionary
{
Text-align: center;
Font-size: 18px;
Clear: both;
Border-top: 3px solid #888;
}
# Loading
{
Border: 1px #000 solid;
Background-color: # eee;
Padding: 20px;
Margin: 100px 0 0 200px;
Position: absolute;
Display: none;
}
# Switcher
{
}
</Style>

<Script type = "text/javascript">

// Call without Parameters
$ (Document). ready (function (){
$ ('# Btn1'). click (function (){
$. Ajax ({
Type: "POST", // WebService access request using Post
ContentType: "application/json", // WebService returns the Json type
Url: "WebService1.asmx/HelloWorld", // address and method name combination of WebService call ---- WsURL/method name
Data: "{}", // here is the parameter to be passed, in the format of data: "{paraName: paraValue}", as shown below
DataType: 'json ',
Success: function (result) {// callback function, result, Return Value
$ ('# Dictionary'). append (result. d );
}
});
});
});

// Call with Parameters
$ (Document). ready (function (){
$ ("# Btn2"). click (function (){
$. Ajax ({
Type: "POST ",
ContentType: "application/json ",
Url: "WebService1.asmx/GetWish ",
Data: "{value1: 'wishful thinking ', value2: 'Good luck', value3: 'niu Niu ', value4: 2009 }",
DataType: 'json ',
Success: function (result ){
$ ('# Dictionary'). append (result. d );
}
});
});
});


// Return the Set (referenced from the network, which is very helpful)
$ (Document). ready (function (){
$ ("# Btn3"). click (function (){
$. Ajax ({
Type: "POST ",
ContentType: "application/json ",
Url: "WebService1.asmx/GetArray ",
Data: "{I: 10 }",
DataType: 'json ',
Success: function (result ){
$ (Result. d). each (function (){
// Alert (this );
$ ('# Dictionary'). append (this. toString () + "");
// Alert (result. d. join ("| "));
});
}
});
});
});

// Return the composite type
$ (Document). ready (function (){
$ ('# Btn4'). click (function (){
$. Ajax ({
Type: "POST ",
ContentType: "application/json ",
Url: "WebService1.asmx/GetClass ",
Data :"{}",
DataType: 'json ',
Success: function (result ){
$ (Result. d). each (function (){
// Alert (this );
$ ('# Dictionary'). append (this ['id'] + "" + this ['value']);
// Alert (result. d. join ("| "));
});

}
});
});
}); ====================
Var aArray = ["sdf", "dasd", "dsa"]; // array $. each (aArray, function (iNum, value) {document. write ("serial number:" + iNum + "value:" + value) ;}); var oObj = {one: 1, two: 2, three: 3 };$. each (aArray, function (property, value) {document. write ("property:" + property + "value:" + value );}); ========================================================== ======
// Return DataSet (XML)
$ (Document). ready (function (){
$ ('# Btn5'). click (function (){
$. Ajax ({
Type: "POST ",
Url: "WebService1.asmx/GetDataSet ",
Data :"{}",
DataType: 'xml', // The returned type is xml, which is different from the preceding Json.
Success: function (result ){
// Demonstrate capture
Try {
$ (Result). find ("Table1"). each (function (){
$ ('# Dictionary '). append ($ (this ). find ("ID "). text () + "" + $ (this ). find ("Value "). text ());
});
}
Catch (e ){
Alert (e );
Return;
}
},
Error: function (result, status) {// if no above capture error occurs, the callback function here will be executed
If (status = 'error '){
Alert (status );
}
}
});
});
});

// Ajax provides feedback to users. The ajaxStart and ajaxStop methods are used to demonstrate callback for ajax tracking related events. The two methods can be added to jQuery objects before and after Ajax callback.
// However, Ajax monitoring is global.
$ (Document). ready (function (){
$ ('# Loading'). ajaxStart (function (){
$ (This). show ();
}). AjaxStop (function (){
$ (This). hide ();
});
});

// Move the cursor to the removal effect. You can use commas (,) to separate multiple elements.
$ (Document). ready (function (){
$ ('Div. click'). hover (function (){
$ (This). addClass ('hover ');
}, Function (){
$ (This). removeClass ('hover ');
});
});


</Script>

</Head>
<Body>
<Form id = "form1" runat = "server">
<Div id = "switcher">
<H2>
JQuery WebServices call <Div class = "button" id = "btn1">
HelloWorld </div>
<Div class = "button" id = "btn2">
Input parameters </div>
<Div class = "button" id = "btn3">
Return set </div>
<Div class = "button" id = "btn4">
Return compound type </div>
<Div class = "button" id = "btn5">
Return DataSet (XML) </div>
</Div>
<Div id = "loading">
Processing the server. Please wait.
</Div>
<Div id = "dictionary">
</Div>
</Form>
</Body>
</Html>
WebService1.asmx. cs

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Using System. Data;

Namespace jQuery. Learning
{
/// <Summary>
/// Summary of WebService1
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
[System. ComponentModel. ToolboxItem (false)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
[System. Web. Script. Services. ScriptService]
Public class WebService1: System. Web. Services. WebService
{
/// <Summary>
/// No parameters
/// </Summary>
/// <Returns> </returns>
[WebMethod]
Public string HelloWorld ()
{
Return "Hello World ";
}

/// <Summary>
/// With Parameters
/// </Summary>
/// <Param name = "value1"> </param>
/// <Param name = "value2"> </param>
/// <Param name = "value3"> </param>
/// <Param name = "value4"> </param>
/// <Returns> </returns>
[WebMethod]
Public string GetWish (string value1, string value2, string value3, int value4)
{
Return string. Format ("Wish you {0}, {1}, {2}", value1, value2, value3, value4 in {3} years );
}

/// <Summary>
/// Return the set
/// </Summary>
/// <Param name = "I"> </param>
/// <Returns> </returns>
[WebMethod]
Public List <int> GetArray (int I)
{
List <int> list = new List <int> ();

While (I> = 0)
{
List. Add (I --);
}

Return list;
}

/// <Summary>
/// Return a composite type
/// </Summary>
/// <Returns> </returns>
[WebMethod]
Public Class1 GetClass ()
{
Return new Class1 {ID = "1", Value = ""};
}

/// <Summary>
/// Return XML
/// </Summary>
/// <Returns> </returns>
[WebMethod]
Public DataSet GetDataSet ()
{
DataSet ds = new DataSet ();
DataTable dt = new DataTable ();
Dt. Columns. Add ("ID", Type. GetType ("System. String "));
Dt. Columns. Add ("Value", Type. GetType ("System. String "));
DataRow dr = dt. NewRow ();
Dr ["ID"] = "1 ";
Dr ["Value"] = "Happy New Year ";
Dt. Rows. Add (dr );
Dr = dt. NewRow ();
Dr ["ID"] = "2 ";
Dr ["Value"] = "everything goes well ";
Dt. Rows. Add (dr );
Ds. Tables. Add (dt );
Return ds;
}

}
// Custom class with only two attributes
Public class Class1
{
Public string ID {get; set ;}
Public string Value {get; set ;}
}
}

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/shuilv2000/archive/2009/11/24/4863977.aspx

 

Summary of Ajax WebServices calling in JQuery
Use javascript:; "onClick =" javascript: tagshow (event, 'ajax '); "target =" _ self "> ajax to access web services.

1. the ajax method must be filled in:

JScript. code
$. Ajax ({type: "POST", // indicate the returned JsoncontentType: "application/json; UTF-8", // college#webservices. asmx web Service name/GetCollegeDepart method name http://www.cnblogs.com/tangself/admin/%22CollegeDepartWebServices.asmx/GetCollegeDepart%22,//strDepartId parameter name collegeId parameter value data: "{strDepartId:" + collegeId + "}", dataType: "json", success: function (result) {varjson = nulltry {if (result) {// The value is retrieved cyclically because ArrayList is returned. $. each (result, funct Ion (I, n) {// ddlDepart is the down menu. Add the new option ddlDepart to the drop-down menu cyclically. options [ddlDepart. length] = newOption (n. collegeappstitle, n. collegeDepartId) ;};}} catch (e) {alert ("error >>" + e. message); return ;}}, error: function (data) {alert (data. status + ">>>" + data. statusText );}});

----
Collegew.webservices. asmx. cs web Service Class

C # code
[WebService (Namespace = "http://tempuri.org/%22)] [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] [ScriptService] publicclasscollege?webservices: System. web. services. webService {publiccollegew.webservices () {// if you use the designed component, uncomment the following line // InitializeComponent ();} [WebMethod] [System. xml. serialization. xmlInclude (typeof (CollegeDepartInfo)] publicArrayList GetCollegeDepart (stringstrDepartId) {CollegeDepartBL. flushCollegeDepartCache (); if (string. isNullOrEmpty (strDepartId) returnnull; ArrayList myList = CollegeDepartBL. getCollegeDepartListByCollegeID (int. parse (strDepartId); returnmyList ;}}

Note:
The ArrayList object is saved as CollegeDepartInfo.
Its Attributes are: stirng college1_title and int CollegeDepartId.
In javascript
DdlDepart. options [ddlDepart. length] = new Option (n. collegepartition title, n. CollegeDepartId );

Option parameters are based on them.

The last important thing is:
The
[ScriptService]
Must be added. Otherwise, ajax cannot call WebService.

 

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/shuilv2000/archive/2009/02/20/3914822.aspx

 

 

 

$. Ajax (properties)
Use the HTTP request (XMLHttpRequest) to load a remote page. This is jQuery's low-level AJAX implementation. For more information about advanced abstraction, see $. set and $. post. $. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly manipulate this object, but it is also available if you need to manually stop the request. Note: Make sure that the server returns the correct MIME type (for example, XML is "text/xml "). If the error MIME type is returned, it will cause serious problems that jQuery cannot handle.

Supported data types include (see the dataType option ):

"Xml": returns an XML document that can be processed by jQuery objects.

"Html": returns HTML in plain text format, including the script tag after the value is evaluated.

"Script": evaluate the response as a Javascript statement and return plain text.

"Json": evaluate the response as JSON and return a Javascript Object.

$. Ajax () carries an object in the form of a parameter-"name/value pair", which is used to initialize and process requests.

The following lists all available "name/value pairs ":

(String) url-the URL to which the request is sent.

(String) type-request type ("POST" or "GET"). The default value is "GET ".

(String) dataType-type of data to be returned from the server. No Default Value: if the server returns XML, it will pass responseXML to the callback function; otherwise, it will pass resposeText to the callback function.

(Boolean) ifModified-the request is successful only when the response is modified after the previous request. It is implemented by checking the value of Last-Modified in the header. The default value is false, that is, ignore

Check part (Number) timeout-overwrite the local latency of the global latency. For example, after all other latencies go through 1 second, start a separate request with a longer latency. For more information about global latency, see $. ajaxTimeout ().

(Boolean) global-whether to trigger a global AJAX event handler for the current request. The default value is true. Setting false can prevent triggering global event processing functions such as ajaxStart and ajaxStop.

(Function) error-the Function called when the request fails. This function will get three parameters: XMLHttpRequest object, a string describing the error type that occurred, and an optional exception object (if any ).

(Function) success-the Function called when the request is successful. This function will get a parameter: The data returned from the server (formatted according to "dataType ). (Function) complete-the Function called when the request is complete. This function will get two parameters: the XMLHttpRequest object and a string that describes the successful request type.

(Object | String) data-the data to be sent to the server. If not, it is automatically rotated into a query string. That is, the string appended to the url of the GET request. To prevent automatic processing, see the processData option.

(String) contentType-set the content = type of the request to be sent. The default value is "application/x-www-form-urlencoded", which can meet the requirements in most cases.

(Boolean) processData-by default, if the data option is passed into an object rather than a string, it will be automatically processed and converted into a query string, to adapt to the default content-type -- "application/x-www-form-urlencoded ". To send DOMDocuments, set this option to false.

(Boolean) async-by default, all requests are sent asynchronously (the value is true ). If you want to use the synchronization method, set this item to false. (Function) beforeSend-a pre-called Function used to set custom headers and other information, receives a unique parameter-XMLHttpRequest object.

Load a remote page using an HTTP request. this is jQuery's low-level AJAX implementation. see $. get, $. post etc. for higher-level processing actions. $. ajax () returns the XMLHttpRequest that it creates. in most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually. note: Make sure the server sends the right mimetype (eg. xml as "text/xml "). sending the wrong mimetype will get you into serious trouble that jQuery can't solve. supported datatypes are (see dataType option): "xml": Returns a XML document that can be processed via jQuery. "html": Returns HTML as plain text, sorted ded script tags are evaluated. "script": Evaluates the response as Javascript and returns it as plain text. "json": Evaluates the response as JSON and returns a Javascript Object $. ajax () takes one argument, an object of key/value pairs, that are used to initalize and handle the request. these are all the key/values that can be used: (String) url-The URL to request. (String) type-The type of request to make ("POST" or "GET"), default is "GET ". (String) dataType-The type of data that you're expecting back from the server. no default: If the server sends xml, the responseXML, otherwise the responseText is passed to the success callback. (Boolean) ifModified-Allow the request to be successful only if the response has changed since the last request. this is done by checking the Last-Modified header. default value is false, ignoring the header. (Number) timeout-Local timeout to override global timeout, eg. to give a single request a longer timeout while all others timeout after 1 second. see $. ajaxTimeout () for global timeouts. (Boolean) global-Whether to trigger global AJAX event handlers for this request, default is true. set to false to prevent that global handlers like ajaxStart or ajaxStop are triggered. (Function) error-A function to be called if the request fails. the function gets passed tree arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occured. (Function) success-A function to be called if the request succeeds. the function gets passed one argument: The data returned from the server, formatted according to the 'ype ype 'parameter. (Function) complete-A function to be called when the request finishes. the function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request. (Object | String) data-Data to be sent to the server. converted to a query string, if not already a string. is appended to the url for GET-requests. see processData option to prevent this automatic process. (String) contentType-When sending data to the server, use this content-type. default is "application/x-www-form-urlencoded", which is fine for most cases. (Boolean) processData-By default, data passed in to the data option as an object other as string will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded ". if you want to send DOMDocuments, set this option to false. (Boolean) async-By default, all requests are send asynchronous (set to true ). if you need synchronous requests, set this option to false. (Function) beforeSend-A pre-callback to set M headers etc ., the XMLHttpRequest is passed as the only argument.

Return Value
XMLHttpRequest

Parameters
Properties (Map): Key/value pairs to initialize the request.
Example
Note:
Load and execute a JavaScript file.

JQuery code:
$. Ajax ({type: "GET", url: "test. js", dataType: "script "})
 
--------------------------------------------------------------------------------

Note:
Save the data to the server and notify the user after saving the data.

JQuery code:
$. Ajax ({type: "POST", url: "some. php ", data:" name = John & location = Boston ", success: function (msg) {alert (" Data Saved: "+ msg );}});
 
--------------------------------------------------------------------------------

Note:
Load data synchronously. The browser is blocked when the request is active. If you must load data synchronously, it is best to use other methods to prevent user interaction, rather than blocking the entire browser.

JQuery code:
Var html = $. ajax ({url: "some. php", async: false}). responseText;
 
--------------------------------------------------------------------------------

Note:
Send an XML document as data to the server. By setting the processData option to false, you can avoid automatically converting data to a string.

JQuery code:
Var xmlDocument = [create xml document]; $. ajax ({url: "page. php", processData: false, data: xmlDocument, success: handleResponse });

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/shuilv2000/archive/2009/11/24/4860787.aspx

 

 

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.