Home > Web Front-end > JS Tutorial > body text

3 ways to implement ajax

php中世界最好的语言
Release: 2018-04-04 15:57:22
Original
2478 people have browsed it

This time I will bring you 3 ways to implement ajax. What are the precautions for implementing ajax? Here are practical cases, let’s take a look.

Ajax: Asynchronous JavaScript and Json objects are often used instead of It belongs to Web front-end development technology and has an extremely close connection with JavaScript. Ajax is a technology that realizes asynchronous communication without refreshing, and this technology can be implemented in many ways. It was first invented by NetScape, the originator of the browser. The LiveScript scripting language was used to enrich the expression of web page elements and enable the web page to present dynamic effects. After subsequent revisions and upgrades, the JavaScript language was born. At the same time, Microsoft also saw the prospects of the Internet and began to He got involved in the Internet industry and launched the JScript language. Unfortunately, it was not as mature as JavaScript and its development was sluggish. In the end, Microsoft's determination for the Internet contributed to MS's long and tortuous acquisition of NS.

Let me mention it here, Dynamic Hyper Text Markup Language is to place javascript in the element node of the Dom tree to provide dynamic display behavior for the elements. (2) Two aspects of Web front-end development Idea:

a. JavaScript + XHR + CSS b. Flash ---> Browser plug-in ---> Flex(Adobe); Silverlight4.0(MS)

1. Ajax: Taking MS's XHR (XMLHttpRequest) as the core ---> Ajax

2. flash: MicroMedia ---> Acquired by Adobe ---> flex (covers ActionScript and Rich Internet Application A combination of other technologies)3. SilverLight: SilverLight launched by Microsoft to compete with flex

Note:

In order to be able to communicate with the server asynchronously in the background For communication, Microsoft added two components to IE: the component responsible for communicating with the server (XMLHTTPRequest) and the XML processing component. Using XML as the carrier of data exchange has advantages in multi-language processing, but the processing cost of XML is relatively high. High, in fact, Json objects are usually used in Ajax to transfer data between the client browser and the server.

The generation process of web pages is actually completed by a set of programs on the server, so that in order to To transfer data between JS language and server-side C# language, .Net provides

Json serialization

and deserializer to provide conversion between server-side C# objects and Json objects. It can be used on the browser side The eval() function obtains the Json string passed by the server and converts it into a Json object.

(3) What problems does Ajax solve

We all know , when the client requests a page from the server, the server first dynamically calculates and generates the page, and then sends it to the client. The client browser compiles and renders the page sequentially.

Without Ajax: If If the page has a user verification control, then when the client browser presents the user verification control, it will wait for the server's verification result. After receiving the result, it can continue to present the page elements. This verification process usually requires operations such as reading the database. This is the so-called synchronization method. This method will cause the web page to appear in a state of suspended animation.After using Ajax: It is also a verification control. After the client submits the verification request, it will continue to present other elements in sequence. . After the verification result is obtained, the DOM object in the memory is modified by javascript on the client side and presented to the user (note: only the DOM object in the memory is modified here, and the page file received by the client is not modified). In this way, Using the asynchronous method, there will be no suspended animation state, and the client also saves the time spent waiting for the server to return results.

(四)Ajax implementation

(The implementation of Ajax in 3, it should be noted that: the effects that Ajax can achieve can be achieved through WebService.)

1. Ajax asynchronous call in Js: a.new b.onreadystatechange (processing responseText) c.open (get mode and post mode) d.send (synchronous call: a.new b.open (get mode and post mode) c.send d.responseText)

//ajax.html

<!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 of Javascript & jQuery</title>
</head>
<body>
<a href="javascript:getData();">Javascript-Ajax: Click me</a><br />
<br />
<br />
<input id="btn" type="button" value="jQuery-Ajax: Clike me"/>
<hr />
<p id="show">
</p>
<script type="text/javascript">
function getData() {
//创建XMLHttpRequest通信对象
var xhr;
if (window.ActiveXObject) { //标准情况下, 只能有两个ActiveXObject对象处理通信过程
xhr =new ActiveXObject("Microsoft.XMLHTTP");
}
elseif (window.XMLHttpRequest) {
xhr =new XMLHttpRequest();
}
else {
thrownew Error("Ajax is not supported by this browser");
}
var elem = document.getElementById("show"); //用来显示处理结果
//使用onreadystatechange事件处理结果
xhr.onreadystatechange =function() {
if (xhr.readyState ==4) { // readyState表示服务器响应状态. 4: 响应接收完毕
if (xhr.status ==200) { // status 表示 http 请求的状态
var json = xhr.responseText; //从请求中回应中获得json串
var obj = eval("("+ json +")"); // 借助 eval 将 json 串转化为对象, 在客户端浏览器必须解析为js对象
elem.innerHTML ="<span>"+ obj.name +"</span>";
}
}
}
//通过open设置请求方式
xhr.open("get", "json.ashx", true); //默认为ture, false表示同步方式
//发送请求
xhr.send(null);
/* 同步方式, false表示不适用异步方式
xhr.open("get", "json.ashx", false);
xhr.send(null);
//处理结果
alert(xhr.responseText);
*/
}
</script>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() { //ready函数, 脚本加载完即执行, 也可以用$(...$("#btn").click...)();加载
$("#btn").click(function showData() { //按钮上添加onclick事件, 事件处理方法为showData()
$("#show").load("jquery.ashx"); //从jquery.ashx中获取数据元素(innerHTML的内容), 并显示在p中
});
});
</script>
</body>
</html>
Copy after login

Then you also need to add a general handler similar to json.ashx in the project to provide relevant data (such as drawing table calendars, database verification, etc.)

//json. ashx

<%@ WebHandler Language="C#" Class="Json"%>
using System;
using System.Web;
publicclass Json : IHttpHandler {
publicvoid ProcessRequest (HttpContext context) {
context.Response.ContentType ="text/plain";
//对于静态内容, 需要禁用浏览器的缓存, 否则老是旧结果
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string name ="Mike";
string jsonFormat ="{{ \"name\": \"{0}\" }}"; //{{、}}是为了避免和Json中的{冲突而采用的特殊转义符
string json =string.Format(jsonFormat, name);
context.Response.Output.Write(json);
}
publicbool IsReusable {
get {
returnfalse;
}
}
}
Copy after login

//jquery.ashx

<%@ WebHandler Language="C#" Class="jquery"%>
using System;
using System.Web;
publicclass jquery : IHttpHandler {
publicvoid ProcessRequest (HttpContext context) {
context.Response.ContentType ="text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
DateTime now = DateTime.Now;
string jqueryFormat ="<span>{0}</span>";
string jquery =string.Format(jqueryFormat, now);
context.Response.Write(jquery);
}
publicbool IsReusable {
get {
returnfalse;
}
}
}
Copy after login

2.1 Using AjaxPro2:

a. Add AjaxPro2 class library (AjaxPro2.dll) b. Add configuration in webconfig File c. Create class library file (cs file) in App_Code to provide Ajax service, and register Ajax in the background cs file corresponding to the page (in the Page_Load event) d. Class in App_Code The library file (in the cs file) writes the processing method with the Ajax tag e. Use the script in the aspx file in the foreground to process the results (modify the DOM object in the memory) and display it on the page

//b. Add configuration file in webconfig

<location path="ajaxpro">
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
<!--
If you need to have Ajax.NET Professional methods running on the
login page you may have to enable your own authorization configuration
here.
-->
<!--
<authorization>
<deny users="?"/>
</authorization>
-->
</system.web>
</location>
Copy after login

//c. Create a class library file (cs file) in App_Code to provide Ajax service, and register Ajax in the background cs file corresponding to the page (in the Page_Load event)

//default.aspx.cs file

protectedvoid Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(CalendarServices)); //AjaxPro会根据注册的类型自动生成脚本
}
Copy after login
//d. Write a processing method with Ajax tag in the class library file (cs file) in App_Code

//CalendarServices.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
publicclass CalendarServices
{
[AjaxPro.AjaxMethod]
publicbool save(string date, string tile, string detail)
{
System.Threading.Thread.Sleep(5000); //用来测试异步
returntrue; //这里为简单, 直接返回true
}
}
Copy after login
//e. Use script in the aspx file in the foreground to process the results (modify the DOM object in memory) and display it on the page

//default. aspx file

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"%>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>
日期:<input id="date" type="text"/><br />
标题:<input id="title" type="text"/><br />
详情:<textarea id="detail" cols="80" rows="5"></textarea>
<hr />
<input id="btn" type="button" value="确定"/>
</p>
<p>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#btn").click(function() {
var date = $("#date").val();
var title = $("#title").val();
var detail = $("#detail").val();
//由AjaxPro生成的js代理, 很像C#中类库的使用, 其中function(result)是异步的结果处理方法
CalendarServices.save(date, title, detail, function(result) {
if (result.error !=null) { //服务器上出现异常
alert(result.error.Message);
}
if (result.value) { //服务器cs文件中的方法返回永真
alert("服务器返回true! ");
}
});
});
});
</script>
</p>
</form>
</body>
</html>
Copy after login
2.2. Boss Ajax used before (may be used to maintain old projects, in fact it is very similar to the second type): a. Reference the Ajax framework class library b. Add configuration in webconfig c. In App_Code Add the Ajax service class in the CS file and register Ajax in the CS file (in the Page_Load event) d. The processing method with the Ajax tag in the CS file in App_Code e. The button binding triggers the JS method f. The JS processing method

//a. Reference the class library Ajax.dll of the Ajax framework

//b. Add configuration to webconfig

<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
</httpHandlers>
Copy after login
//c. Register Ajax in the CS file (in the Page_Load event )

Ajax.Utility.RegisterTypeForAjax(typeof(SysBase_UserEdit)); //SysBase_UserEdit是页面文件名称
Copy after login
//d. Processing method with Ajax tag in CS file in App_Code

[Ajax.AjaxMethod]
public DataSet getRoleData(int Roleid)
{
DataSet ds =new DataSet();
ds = r.SelectRoleData(string.Format(" and id={0}", Roleid));
return ds;
}
Copy after login
//e. Method for triggering JS by button binding

this.DDLRole.Attributes.Add("onpropertychange", "onCommandInputPropertyChange();"); //在Page_Load事件中基于Attribute为按钮绑定方法, 在aspx文件中手动添加也可以
Copy after login
//f. JS processing method

<script> 
  function onCommandInputPropertyChange(){ 
    if (event.propertyName == "value"){ 
      var cmdInput = event.srcElement; 
      if (cmdInput.value != 0){ 
        //alert(cmdInput.value); 
    BindRoleName(cmdInput.value);    
      } 
    } 
  } 
  //绑定角色名 
  function BindRoleName(RoleID){ 
  //SysBase_UserEdit是aspx页面的名称 
    SysBase_UserEdit.getRoleData(RoleID,get_AllName); 
  } 
  function get_AllName(response){ 
    var AllName = document.getElementById("DDLAjax"); 
    AllName.length = 0; 
    if (response.value != null){ 
      var ds = response.value; 
      if(ds != null && typeof(ds) == "object"){      
        var name = ds.Tables[0].Rows[0].rolename; 
      var id = ds.Tables[0].Rows[0].id;      
      AllName.options.add(new Option(name,id)); 
    } 
  } 
  } 
</script>
Copy after login
3. VS2008 integrated Ajax:

a. For VS2005, you need to install the plug-in (Microsoft ASP.NET 2.0 AJAX Extensions) b. Next to the Form element Place the ScriptManager control c. At the first position of the table element to be refreshed, wrap it with UpdatePanel and ContentTemplate d. Place the trigger element between ContentTemplate and UpdatePanel at the end of the table element, and register the Ajax trigger button e. Reference the class library Ajax2 f.VS2005 Need to configure webConfig

//d. Place trigger element between ContentTemplate and UpdatePanel at the end of table element, register Ajax trigger button (btn_Search, btn_Delete are buttons)

<Triggers>
<asp:AsyncPostBackTrigger ControlID="AspNetPager1"/>
<asp:AsyncPostBackTrigger ControlID="btn_Search"/>
<asp:AsyncPostBackTrigger ControlID="btn_Delete"/>
</Triggers>
Copy after login
//f . VS2005 needs to configure webConfig

<httpHandlers>
<!-- 调用AjaxPro.2-->
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
Copy after login
============================ dividing line======== ====================

Regarding the first type: Ajax asynchronous call in Js, I will add some stuff and won’t start it separately

About parameter passing:

1.

Pass parameters in get mode, and the parameters are stored in the URL, for example:

xhr .open("get", "json.ashx?name=xxx", true);

xhr.send(null);

On the server side (json.ashx background code), you can use HttpContext Type parameter object context to obtain, the acquisition method is context.Request.QueryString["name"]....etc. (see it in debugging state)

2.

Pass parameters in post method, The parameters are stored in the body of the request package, for example:

xhr.open("post","json.ashx",true);

xhr.send("xxx");

or

xhr.send("name=xxx");

Corresponding server side (json.ashx background code), for "non-key-value pairs" and " in 2 There are two ways to obtain key-value pairs:

Non-key-value pairs: Use context.Request.InputStream to obtain them, such as:

System.IO.Stream stream = context.Request.InputStream;
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
string strParam = sr.ReadToEnd();
Copy after login

If it involves encoding conversion, you will need to adjust it yourself.

Key-value pair: Use context.Request.Form["name"]... to get

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!

Recommended reading:

How to prevent the ajax callback from being intercepted by the browser when opening a new form

jQuery+AJAX calls the background of the page

The above is the detailed content of 3 ways to implement ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template