Learn more about. NET and Ajax in a detailed case summary

Source: Internet
Author: User
First understand what Ajax is.

Ajax is not a new programming language, but rather a technique for creating better, faster, and more interactive Web applications.
With AJAX, your JavaScript can use JavaScript's XMLHttpRequest object to communicate directly with the server. With this object, your JavaScript can exchange data with the Web server without overloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the Web server, which allows the Web page to request a small amount of information from the server, rather than the entire page.

When it comes to JavaScript, we all think of browser compatibility issues, and Ajax needs to take this into account. Because different browsers use the same class of JavaScript for the web, the effect will not be the same. The following is not nonsense, the direct introduction of code for your reference.
{
var xmlhttp;//non-IE browser create XMLHttpRequest object
if (window. XMLHttpRequest) {
XMLHTTP = new XMLHttpRequest ();
}
IE Browser creates XMLHttpRequest object
if (window. ActiveXObject) {
try {
XMLHTTP = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (e) {
try {
XMLHTTP = new ActiveXObject ("MSXML2. XMLHTTP ");
}
catch (ex) {}
}
}
if (!xmlhttp) {
Alert ("Create XMLHTTP Object Exception");
return false;
}
Xmlhttp.open ("POST", "getdate.ashx?nd=" + New Date (), false); Make a request to a server page
Xmlhttp.open ("GET", "URL", false);

Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {//If the status code shows success
document.getElementById ("Text1"). Value = Xmlhttp.responsetext;
XXXXX = xmlhttp.responsetext;//Here we can return the parameters we passed to our HTML tags, or other variables to handle the problem
//responsetext the text returned for the server
else {
Alert ("The AJAX server returned an error");
}
}
}
Xmlhttp.send ();//Start Sending request
This is just the foreground code, the code is enough, to achieve the function of the partial refresh page, the rest of the code is based on the project is different, I do not need to introduce.

You see this code feel how, for just learning JavaScript or Ajax classmate, want to remember these code, it is really difficult ah, and how to understand these things, I basically have comments above, we generally can understand. But if each page needs a local refresh, it will feel like every page to write such code is not very troublesome Ah, jquery helped us to complete a lot of things, so that we can reduce the difficulty of developing projects, the following is the use of jquery code:

$.ajax ({
Type: "POST",
URL: "some.php",
Data: "Name=john&location=boston",
Success:function (msg) {
Alert ("Data Saved:" + msg);
}
}); another way

$.post ("test.php", {name: "John", Time: "2pm"},
function (data) {
Alert ("Data Loaded:" + data);
}); It is not very simple ah, here we call him to write the function, we can implement our non-refresh code, now feel is not a refresh page is not very simple, but we just pass a small data, if it is difficult to extract data from the database, the following introduction of my part of the code, Let us think about

Here is the foreground and background code that I implemented without a refresh comment and displayed:

<%@ page language= "C #" autoeventwireup= "true" codebehind= "AjaxComment.aspx.cs" inherits= " Ajax Learning. No refresh comments. AjaxComment1 "%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<title></title>
<script src= ". /js/jquery-1.9.1.js "type=" Text/javascript "></script>
<script type= "Text/javascript" >
$ (function () {
$ ("#btnComment"). Click (function () {
var comment = $ ("#txtComment"). Val ();

$.post ("Ajaxcomment.ashx", {"msg": Comment},
function (data, status) {
if (Status! = "Success") {
Alert ("Comment failed, please retry");
Return
}
if (data = = "OK") {
var newcomment = $ ("<li> comment Date:" +new date (). toString () + ", IP:," + "native" + "content:" +comment+ "</li>");
$ ("#ulComment"). Append (NewComment);
Alert ("comment published successfully");
}
else {
Alert ("The comment is published in question");
}
});
});
});
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server"
Deletemethod= "Delete" insertmethod= "Insert"
oldvaluesparameterformatstring= "original_{0}" selectmethod= "GetData"
Typename= "Ajax Learning. Datasetcommenttableadapters.t_commenttableadapter "
updatemethod= "Update" >
<DeleteParameters>
<asp:parameter name= "original_id" type= "Int64"/>
</DeleteParameters>
<InsertParameters>
<asp:parameter name= "IP" type= "String"/>
<asp:parameter name= "MSG" type= "String"/>
<asp:parameter name= "postdate" type= "String"/>
</InsertParameters>
<UpdateParameters>
<asp:parameter name= "IP" type= "String"/>
<asp:parameter name= "MSG" type= "String"/>
<asp:parameter name= "postdate" type= "String"/>
<asp:parameter name= "original_id" type= "Int64"/>
</UpdateParameters>
</asp:ObjectDataSource>
<ul id= "Ulcomment" >
<asp:repeater id= "Repeater1" runat= "Server" datasourceid= "ObjectDataSource1" >
<ItemTemplate>
<li> Comment Date: <% #Eval ("postdate")%>,ip:<% #Eval ("IP")%>, Content: <% #Eval ("MSG")%><br/></ Li>
</ItemTemplate>
</asp:Repeater>
</ul>
<textarea id= "txtcomment" cols= "rows=" ></textarea><br/>
<input id= "btncomment" type= "button"
Value= "Submit"/>
</div>
</form>
</body>

Background code (AJAXCOMMENT.ASHX)

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using AJAX learning. Datasetcommenttableadapters;
Using System.Web.Services;
Namespace Ajax learning. No Refresh Comments
{
<summary>
Summary description of Ajaxcomment
</summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
public class Ajaxcomment:ihttphandler
{

public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
String msg = context. request["MSG"];
New T_commenttableadapter (). Insert (context. Request.userhostaddress,msg,datetime.now.tostring ());//Use a strongly typed dataset
Context. Response.Write ("OK");
}

public bool IsReusable
{
Get
{
return false;
}
}
}
Everyone read the foreground code is not a question, if you pass a lot of fields, many properties of data, what to do, if each data is such a split (), then the big project will certainly be tired, the following jquery has helped us do a good thing, is the use of JSON, Below I introduce my JSON code using no refresh comments

Front Code:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<script src= ". /js/jquery-1.9.1.js "type=" Text/javascript "></script>
<script type= "Text/javascript" >
$ (function () {
$.post ("Pagedservices.ashx", {"Action": "Getpagecount"}, function (data, status) {
for (var i = 1; I <=data; i++) {
var td = $ ("<td><a href=" > "+ i +" </a></td> ");
$ ("#trPage"). Append (TD);
}
$ ("#trPage TD"). Click (function (e) {
E.preventdefault ();//Do not direct the link address
$.post ("Pagedservices.ashx", {"Action": "Getpagedata", "Pagenum": $ (This). Text ()},
function (data, status) {
var comments = $.parsejson (data);
$ ("#ulComments li"). Remove ();
for (var i = 0; i < comments.length; i++) {
var comment = Comments[i];
var li = $ ("<li>" + comment. Id + "---" + comment. IP + "---" + comment. MSG + "---" + comment. Postdate + "</li>");
$ ("#ulComments"). Append (LI);
}
});
});
});
});
</script>
<body>
<ul id= "Ulcomments" ></ul>
<table><tr id= "Trpage" ></tr></table>
</body>

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Services;
Using AJAX learning. Datasetcommenttableadapters;
Using System.Web.Script.Serialization;
Namespace Ajax learning. No Refresh Paging
{
<summary>
Summary description of Pagedservices
</summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
public class Pagedservices:ihttphandler
{

public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
Context. Response.Write ("Hello World");
String Action=context. Request["Action"];
var adapter = new T_commenttableadapter ();
if (action = = "Getpagecount")
{

int Count=adapter. SelectCount (). Value;
int PAGECOUNT=COUNT/10;
if (count%10!=0)
{
pagecount++;
}
Context. Response.Write (PageCount);
}
else if (action== "Getpagedata")
{
String Pagenum=context. request["Pagenum"];
int ipagenum = Convert.ToInt32 (pagenum);
var data = adapter. Getpageddata ((iPageNum-1) * 1, Ipagenum * 10);
List<comments> list=new list<comments> ();
foreach (var row in data)
{
List. ADD (New Comments () {Id = (int) row. Id, IP = row. IP, MSG = row. MSG, postdate = row. Postdate,});
}
JavaScriptSerializer JSS = new JavaScriptSerializer ();
Context. Response.Write (JSS. Serialize (list));
}
}

public bool IsReusable
{
Get
{
return false;
}
}
}

public class Comments
{
public int Id {get; set;}
public string Ip{get;set;}
public string Msg{get;set;}
public string Postdate{get;set;}
}
} So we really save a lot of effort Ah, is not jquery is very powerful ah ...

Then, Microsoft feels that I have to encapsulate my Ajax, so that developers do projects to make it easier, Microsoft really helps us to encapsulate one, but for the master, we do not want to use, feel that the code is too stiff, a little inflexible, I followed the introduction of code, For beginners ' Reference: (You can use AJAX to quickly develop new projects as well as beginners who don't know how Ajax works)

<%@ page language= "C #" autoeventwireup= "true" codebehind= "UpdatPanel.aspx.cs" inherits= "Ajax learning. Updatepanel.updatpanel "%>

<%@ Register assembly= "AjaxControlToolkit" namespace= "AjaxControlToolkit" tagprefix= "CC1"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<title></title>
<body>
<form id= "Form1" runat= "Server";
<asp:scriptmanager id= "ScriptManager1" runat= "Server",
</asp:scriptmanager>
<div>
<asp:textbox id= "TextBox1" runat= "Server" ></ASP:TEXTBOX>
<asp:button id= "Button1" runat= "Server" text= "Normal Refresh page displays current time"
onclick= "Button1_Click"/>
</div>
<div>
<asp:updatepanel id= " UpdatePanel1 "runat=" server "
<contenttemplate>
<asp:textbox id=" TextBox2 "runat=" Server "> </asp:textbox><asp:button id= "Button2" runat= "Server" onclick= "button2_click"
text= "Ajax No refresh Display current Time"/
<br/>
</contenttemplate>
</asp:updatepanel>
</div>
</form>
</body>

<%@ page language= "C #" autoeventwireup= "true" codebehind= "WCF_Ajax.aspx.cs" inherits= "Ajax learning. WCF's Ajax.wcf_ajax "%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<title></title>

<script language= "javascript" type= "Text/javascript" >
<! [cdata[

function Button1_onclick () {
Personservice.getperson (1, function (data) {
Alert (data. Name);
},
function () {
Alert ("failure");
});
}

]]>
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>

<asp:scriptmanager id= "ScriptManager1" runat= "Server" >
<Services>
<asp:servicereference path= "./personservice.svc"/>//attention to path handling issues,
</Services>
</asp:ScriptManager>
<input id= "Text1" type= "text"/>
<input id= "Button1" type= "button" value= "button" onclick= "Return Button1_onclick ()"/>
<br/>

</div>
</form>
</body>

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Runtime.Serialization;
Using System.ServiceModel;
Using System.ServiceModel.Activation;
Using System.ServiceModel.Web;
Using System.Text;

Namespace Ajax Learning. Ajax of WCF
{
[ServiceContract (Namespace = "")]
[Aspnetcompatibilityrequirements (Requirementsmode = aspnetcompatibilityrequirementsmode.allowed)]
public class Personservice
{
To use HTTP GET, add the [WebGet] attribute. (Default Responseformat is Webmessageformat.json)
To create an operation that returns XML,
Please add [WebGet (Responseformat=webmessageformat.xml)],
and include the following lines in the action body:
WebOperationContext.Current.OutgoingResponse.ContentType = "Text/xml";
[OperationContract]
public void DoWork ()
{
Add an action implementation here
Return
}

[OperationContract]
Public person Getperson (int id)
{
return new person () {name= "Tom", age=30};
}

Add more actions here and mark them with [OperationContract]
}

public class Person
{
public string Name {get; set;}
public int age{get;set;}

}
}



Learn more about the. NET and Ajax detailed case summary related articles please follow topic.alibabacloud.com!

  • 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.