Explore the use of jQuery ajax scenarios of c-sharp

  • 2020-03-30 00:41:21
  • OfStack

One: jQuery. Ajax syntax foundation

The jQuery ajax ([options])

Overview: loading remote data via HTTP requests.

JQuery's underlying AJAX implementation. Easy to use high - level implementation see $. Get, $. Post, etc. $.ajax() returns the XMLHttpRequest object it created. More flexibility can be gained with this approach.

The data type
The $.ajax() function relies on the information provided by the server to process the returned data. The dataType option also lets you specify different ways of handling data. Where the data returned by the text and XML types is not processed. If specified as an HTML type, any embedded JavaScript is executed before the HTML is returned as a string. If you specify a json type, the retrieved data is parsed as a JavaScript object and the constructed object is returned as the result. Data is sent to the server, and by default, Ajax requests use the GET method. If you want to use the POST method, you can set the value of the type parameter. This option also affects how the content in the data option is sent to the server.

Use scenario 1:
Save data to server, display information on success. JQuery code:
$. Ajax ({
    Type: "POST",
    Url: "some PHP",
    Data: name = John&location = "Boston",
    Success: the function (MSG) {
        Alert ("Data Saved: "+ MSG);
    }
});

Use scenario 2:
Description: loads the latest version of an HTML web page. JQuery code:
$. Ajax ({
  Url: "the test. The HTML",
  Cache: false,
  Success: the function (HTML) {
      $(" # results "). Append (HTML);
  }
});

Load (url, [data], [callback])
Overview: loads the remote HTML file code and inserts it into the DOM.
The default is GET - automatically converts to POST when passing additional parameters.

Use scenario 1:
Description: load the contents of the feeds.html file. JQuery code:
$(" # feeds "). The load (" feeds. HTML ");

JQuery. Get (url, [data], [callback], [type]) and jQuery. Post (url, [data], [callback], [type])

Overview: via remote HTTP GET or POST  Request to load information.
This is a simple GET or POST request function to replace the complex $.ajax. The callback function is called when the request succeeds. If you need to execute a function in the event of an error, use $.ajax.
Description: displays the test.aspx return value (HTML or XML, depending on the return value) and adds a set of request parameters. JQuery code:
$.get("test.aspx", {name: "John", time: "2pm"},
  The function (data) {
      Alert ("Data Loaded: "+ Data);
});
$.post (" test. Aspx, "{name:" John ", time: 2 PM ""},
  The function (data) {
      Alert ("Data Loaded: "+ Data);
});

The above is the basic syntax, we just want to do a first understanding, if you are familiar with it, then we will start a step-by-step discussion of the above methods and usage scenarios.

Two: jQuery. Ajax with ASP.NET actual practice

First, create the default.aspx page as the requesting page and get the return value. The code default.aspx of the page is:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JqueryAjax2._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script src="jsjquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function() {
        $('#showinfo').click(function() {
            var data = { key1: " Liu Mingfeng ", key2: " Lin looked at " };
            $.ajax({
                type: "POST",
                url: "response.aspx",
                data: data,
                dataType: "text",
                success: function(msg) {
                    $("#ajax").append(msg);
                }
            });
            $.ajax({
                url: "test.htm",
                cache: false,
                success: function(html) {
                    $("#resulthtml").append(html);
                }
            });
            $("#load").load("test.htm");
            $.get("response.aspx", data, success1, "text");
            $.get("TextJson.txt", success3, "json");
            $.post("response.aspx", data, success2, "text");
            function success1(message) {
                $("#get").append(message);
            }
            function success2(message) {
                $("#post").append(message);
            }
            function success3(siteData) {
                var result = "<li>334 The number one bed :" + siteData.key1 + "</li>";
                result += "<li>334 2 bed :" + siteData.key2 + "</li>";
                result += "<li>334 3 bed : " + siteData.key3 + "</li>";
                result += "<li>334 4 bed : " + siteData.key4 + "</li>";
                $("#result").html(result);
            }
        });
    });
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
<input type="button" id="showinfo" value="show info"></input> 
     <ul id="ajax">ajax:</ul>
     <ul id="resulthtml">resulthtml:</ul>
     <ul id="load">load:</ul>     
     <ul id="get">get:</ul>
     <ul id="post">post:</ul>
     <ul id="result"></ul>

</body>
</html>

Default.aspx.cs has no code in it, just Default.
There are three roles for the recipient of the request: response.aspx page, test.htm static page, and textjson.txt.

Response.aspx page: mainly obtains the data submitted by the client on the server side and returns the data to the client side.
Test.htm static page: the main part of the client to load the latest version of the HTML page.
Textjson.txt: is stored as data in a file for clients to access asynchronously.

Response.aspx page code, response.aspx is:

< % @page Language="C#" AutoEventWireup="true" CodeBehind="response.aspx.cs" assits =" queryajax2.response "%>

There is no HTML code, because you mainly get the data submitted by the client on the server side and return the data to the client side. You do not need to display the HTML content, so you can have no HTML tags.
Response.aspx.cs page code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace JqueryAjax2
{
    public partial class response : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string str = Request["key1"];
            Response.Write("success" + str);
        }
    }
}

In the code, you can see how the server side gets the data submitted by the client and returns it to the client.

The code for the static page of test.htm is:


<!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></title>
</head>
<body>
test.html
</body>
</html>

When a static page is requested, it is returned to the client as HTML, using $("#resulthtml").append(HTML); This method displays the contents of the test.htm static page.

Textjson.txt contains a section of text in json format:

{    "Key1" : "liu mingfeng",     "Key2" : "linwang",     "Key3" : "Chen wenjie",     "Key4" : "geng dianjia"}

What is returned after being accessed is data in json format, which is automatically converted into objects when the client gets the json.

Well, jQuery's asynchronous usage scenario basically meets our needs, so give it a try yourself.


Related articles: