Home  >  Article  >  Web Front-end  >  JavaScript learning summary JS, AJAX application_javascript skills

JavaScript learning summary JS, AJAX application_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:16:481436browse

 1. Introduction to AJAX

AJAX (transliterated as: Ajax) = Asynchronous JavaScript and XML (asynchronous JavaScript and XML), refers to a web development technology for creating interactive web applications, that is, without reloading the entire web page , technology that can update some web pages. AJAX is not a new programming language, but a new way of using existing standards. It is a technology for creating fast and dynamic web pages. AJAX allows web pages to update asynchronously by exchanging a small amount of data with the server in the background. This means that certain parts of the web page can be updated without reloading the entire web page. Traditional web pages (not using AJAX) must reload the entire web page if they need to update content or user registration information, submit forms, etc. So AJAX is an art of exchanging data with the server and updating part of the web page, so we must master the technology of AJAX.

AJAX is based on existing Internet standards and uses them in conjunction:

 ①, XMLHttpRequest object (asynchronous exchange of data with the server)

 ②、JavaScript/DOM (information display/interaction)

 ③、CSS (define styles for data)

 ④、XML (as the format for converting data)

The core of AJAX is the JavaScript object XMLHttpRequest, which is a technology that supports asynchronous requests. That is, XMLHttpRequest gives us the ability to use JS to make requests to the server and process responses without blocking the user. Through this object, JS Data can be exchanged with the Web server without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, which allows a web page to request small pieces of information from the server rather than the entire page. AJAX is a browser technology that is independent of web server software, which means AJAX applications are browser and platform independent! Can be used to create more dynamic applications

 So, simply put, AJAX allows JS to read data on the server. Its function is to read or send data to the server without refreshing the page. It can be used to communicate interactively with JSON files, dynamically communicate with databases, and create more dynamic applications. The most common application is user login. When logging in, he can determine whether the user input is correct. If the input is correct, the user information will be displayed directly. If the input is incorrect, an error message will be prompted without refreshing the page.

2. Configure the server

AJAX application updates asynchronously and reads data on the server. So what exactly is a server? In fact, the server is equivalent to a PC. When we usually browse the web, we only need to enter the corresponding URL in the address bar to browse the corresponding page. These pages cannot be stored in a personal computer, so how big a hard drive is needed, and also There are other influencing factors, so these web pages are stored on corresponding servers, such as Baidu servers and Sina servers. In fact, servers are not much different from the computers we usually use. Personal computers can also be used as servers, or even mobile phones. Such things can also be used as servers. For example, if we use a mobile phone to transfer photos to a computer, we can easily complete the transfer process by using WIFI or the functions provided by Tencent without using a data cable. At this time, the mobile phone acts as a server. It's just that the performance is relatively poor and it only provides services to this machine. Then the web server can provide services to many people at the same time, and its performance is more powerful.

When learning AJAX, you must configure a personal server, which means building a server program on this machine to facilitate us to debug the code. WAMP is usually used to build servers. There are many local server building programs. You can choose the one you like to build. Here is WAMP as an example. WAMP is the Apache + Mysql + PHP integrated installation environment under Windows, that is Server programs on the Win platform usually use the WampServer server software. What I installed here is WampServer 2.5. You can search wamp on Baidu to find the 2.5 version to download and install. It is recommended to install the program on the D drive. After the installation is completed, open the program. There is a W icon in the lower right corner of the desktop. It is usually green. You can Right-click on the icon and select the penultimate option to switch to Chinese. After the switch is completed, the next step is to configure. The following is the configuration method I found online, and there is no problem in using it. It saves me writing it here. , now WampServer has been updated to version 3.0. According to the installed version, search for configuration methods on Baidu, there are piles of them.

First, open the installation directory with an editor: D:wampbinapacheapache2.4.9confhttpd.conf file

Found on line 516 or search keywords:

#Include conf/extra/httpd-manual.conf

Remove the pound sign in front.

Then, open: D:wampbinapacheapache2.4.9confextrahttpd-vhosts.conf file

Add the following content at the end of the code:

<VirtualHost *:80>
DocumentRoot "D:/wamp/www"
ServerName www.abc.com
ServerAlias www.abc.com abc.com
<Directory "D:/wamp/www">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

 www.abc.com is a personal site address and can be defined by yourself.

Finally, open: C:WindowsSystem32driversetchosts file

Added: 127.0.0.1 www.abc.com

Restart WAMP.

When you need to do testing, save the page under the path D:/wamp/www, save the file name as index.html, and then enter abc.com in the browser address bar to open the page you just saved.

If the opening is unsuccessful, you can search on Baidu for a solution. Port 80 may be occupied.

It should be noted here that files placed under the server cannot be named in Chinese.

  3. AJAX basics

First, let’s look at an example of an AJAX application: requesting and displaying a static TXT file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-">
<title>AJAX 实例</title>
<script>
function ajax(){
var oAjax = new XMLHttpRequest();
oAjax.onreadystatechange = function (){
if(oAjax.readyState == && oAjax.status == ){
alert(oAjax.responseText);
}
}
oAjax.open('GET', 'ajax/demo.txt', true);
oAjax.send();
}
</script>
</head>
<body>
<button type="button" onclick="ajax()">读取</button>
</body>
</html> 

We need to save the page in the www root directory of the WAMP installation directory, and create a new folder named ajax to store the TXT file, named demo.txt. You can enter any text in the file for demonstration. . Then open the page in the browser through our customized personal site, and when the read button is clicked, the content in the TXT file pops up.

Through the above example, we can see that the actual function of AJAX is to read a file from the server and return the content of the file to us for us to process.

What needs to be noted here is the character set encoding issue. When using AJAX, all files must be in a unified encoding format, including HTML, JS files and read files, such as UTF-8 or GB2312 , the TXT file used for demonstration in the above example, the default input is English, and the default encoding is ANSI when saving. If we input Chinese characters and do not change it to the same encoding format UTF-8 as the page when saving, then click the button Afterwards, garbled characters are displayed on the web page, so when saving, be sure to switch the encoding format of the file.

Let’s analyze how AJAX works.

  4. XHR creates objects

 XHR is the abbreviation of XMLHttpRequest, which is the basis of AJAX and is used to exchange data with the server in the background.

All modern browsers (IE7+, Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects. Older versions of IE browsers (IE6) use ActiveXObject. In order to be compatible with various browsers, you can make a judgment. If If the XMLHttpRequest object is supported, the object is created. If it is not supported, an ActiveXObject is created.

var oAjax;
// IE+, Firefox, Chrome, Opera, Safari
if(window.XMLHttpRequest){
oAjax = new XMLHttpRequest();
}
// IE
else{
oAjax = new ActiveXObject("Microsoft.XMLHTTP");
} 

Since all modern browsers and IE higher version browsers support the XMLHttpRequest object, there is no need to do compatibility processing when creating the object. Here is just a look. In the IE browser, ActiveX means plug-in, which means that AJAX in IE6 is implemented through a plug-in. Although it is a plug-in, it is installed by default in the IE6 browser.

In the above code, window.XMLHttpRequest is used when making judgments. We all know that global variables are an attribute on window. In JS, if you use undefined variables, an error will be reported, such as: alert(a ). And if you use an undefined property, no error will be reported, but undefined, for example: alert(window.a). IE6 does not support XMLHttpRequest, so if you use it directly, an error will be reported. If you define it as a property of window, it will be undefined. Undefined represents false in the if judgment statement, which is fasle, and this is exactly what we need. .

  5. Connect to the server

To send the request to the server, we use the open() and send() methods of the XMLHttpRequest object:

oAjax.open('GET', 'ajax/demo.txt', true);
oAjax.send();

open(method, url, async) specifies the type of request, URL and whether to process the request asynchronously. The first parameter, method, is used to specify the type of request, GET or

POST . The second parameter URL is used to set the address of the file on the server. The file can be any type of file, such as .txt, .xml and .json, or a server script file, such as .php (before returning the response, able to perform tasks on the server). The third parameter, async, is used to define whether to transmit asynchronously, true (asynchronous) or false (synchronous).

 send(string) is used to send the request to the server, and the parameter string is only used for POST requests.

Let’s look at two questions.

 (1), GET or POST?

 GET and POST are often used to submit forms, and we are no strangers to them. The default method for form submission is GET.

Compared to POST, GET is simpler and faster, and works in most cases.

However, please use POST requests in the following situations:

 ①. Cache files cannot be used (updating files or databases on the server).

 ②. Send a large amount of data to the server (POST has no data limit).

 ③When sending user input containing unknown characters, POST is more stable and reliable than GET.

The most practical judgment method: GET is used to obtain data, such as browsing posts, and POST is used to upload data, that is, to transfer data to the server, such as user registration.

The difference between GET and POST:

 GET: Transmits data in URL, with weak security and small capacity. Generally, the maximum length of URL is 4K to 10K, and the length is limited.

POST: does not transmit data in the URL. It is relatively secure and has large capacity. The capacity can reach 2G. If it is larger, you can use controls. The only real security is the https protocol.

Caching: GET is cached, POST is not cached.

Therefore, AJAX is generally a GET method. Of course, there are many methods besides GET and POST methods, but these two are the most commonly used.

In the basic AJAX example, because we use GET requests, there is another problem is the cache problem. The so-called cache is just like after a website is opened once, it will be faster if it is opened again. This is Thanks to the cache, the cache is actually a website. When it is opened for the first time, it is actually requested from the server. After that, it is read locally. Reading data from the hard disk is definitely faster, at least Much faster than the Internet. So according to this, isn't caching a good thing? What's the problem? Let's take a look at the example in AJAX. We have opened it once, which means there is already a local cache. So what will happen if we add some text to the TXT file at this time? You will find that after clicking the button, the added text will not be displayed and will be displayed after a while. This is a cache problem. The cache of Chrome and FF is not serious, but the cache of IE browser is more serious. This problem often causes us some troubles. For example, it is a stock website that needs to update the latest stock price in real time. This price is always changing. If caching is not blocked, it will be difficult to update the price in real time, so If it is data that changes frequently, you need to prevent caching. The working principle of caching is to cache according to the URL. The same address is read once, so to prevent caching, just keep the URL changing, that is, add a unique ID to the URL.

  我们平时在浏览网页时,都见过这种样子,比如在使用百度搜索时,百度域名后边跟了个问号,然后是一堆什么等于什么:https://www.baidu.com/s?wd=前端&rsv_spt=1&rsv_iqid=0xe9146bd400052360&issp=1&,这个问号后边的数据就被称为 GET 数据。如果我们给 TXT 文件后边也加入 GET 数据,http://abc.com/ajax/demo.txt?a=2,或者可以自定义什么等于什么,这样对文件的显示内容是没有任何影响的,那么对于缓存的问题,我们就可以对 oAjax.open('GET', '/ajax/demo.txt', true) 第二个参数 URL 做一些修改,'ajax/demo.txt?t=' + Math.random(),Math.random() 方法返回一个 0-1 之间的随机小数,那么每次返回的都不同,也可以添加 'ajax/demo.txt?t=' + new Date().getTime(),getTime()用于获取当前的时间戳,也就是1970年元旦到当前的毫秒数,那么使用 get Time() 返回的数据每一次都不一样,因为是毫秒数,所以1秒之内就有很多种可能,他的值一直在变,这样就能很好的解决缓存问题。

  这里要注意的是,在使用 GET 请求时,为了避免只是得到缓存的结果,需要向 URL 添加一个唯一的 ID,使 URL 每次都不一样。

  如果需要通过 GET 方法发送信息,可以把信息添加在 URL 中。

  如果需要像 HTML 表单那样传输 POST 数据,可以使用 setRequestHeader() 来添加 HTTP 头,然后在 send() 方法中规定发送的数据。

  setRequestHeader(header, value) 用于向请求添加 HTTP 头,第一个参数 header 规定头的名称,比如 Content-type,第二个参数规定头的值。

  (2)、true 还是 false?

  同步和异步,在现实生活中,同步的意思为多件事一起做,而异步为一件件来,也就是不同步。但是在 JS 中同步和异步的概念和现实生活中恰恰是相反的,同步的意思为事情一件件来,先干完一件事再干另一件事,而异步则为多个事情可以一起做,而 AJAX 天生就是用来做异步操作的,如果 AJAX 工作在同步的方式下,也就是事情得一件一件来,当发出一个请求后,因为网速有点慢,这个请求在1分钟后才得到响应,那么在这个请求结束之前,页面中所有的按钮、链接、文字等全都跟死了一样,就完全没法操作了。而如果是异步的话,就没问题了,比如你发微博,发出去之后因为网速慢没有更新过来,那么在他更新之前,还可以做其他操作。

  AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML),XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true,所以 AJAX 一般都为异步传输。对于 Web 开发者来说,发送异步请求是一个巨大的进步,很多在服务器执行的任务都相当费时,在 AJAX 出现之前,这可能会引起应用程序挂起或者停止。

  而通过 AJAX,JS 无需等待服务器的响应,而是在等待服务器响应时执行其他脚步,当响应就绪后对响应进行处理。

  当使用异步时,也就是 async = true 时,必需规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

oAjax.onreadystatechange = function (){
if(oAjax.readyState == && oAjax.status == ){
alert(oAjax.responseText);
}
}
oAjax.open('GET', 'ajax/demo.txt&#63;t=' + Math.random(), true);
oAjax.send();

  如需使用 async=false,请将 open() 方法中的第三个参数改为 false 。

  不推荐使用同步传输,但是对于一些小型的请求,也是可以的。

  这里需要注意,JS 会等到服务器响应就绪才继续执行,如果服务器繁忙或缓慢,应用程序会挂起或停止。

  当使用 async = false 时,可以不用编写 onreadystatechange 函数,把代码放到 send() 语句后面即可:

oAjax.open('GET', 'ajax/demo.txt', false);
oAjax.send();
document.getElementById('div').innerHTML = oAjax.responseText;

  6、服务器响应

  XMLHttpRequest 对象的 responseText 或 responseXML 属性用于获得来自服务器的响应,也就是获取从服务器返回的信息。

  如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,就使用 responseXML 属性。

  如果来自服务器的响应并非 XML,就使用 responseText 属性,该属性返回字符串形式的响应,因此可以直接使用:

document.getElementById('div1').innerHTML = oAjax.responseText;

  这里说到 XML ,我们就不得不提一下 AJAX 数据,也就是数据类型,数据类型可以分为很多种,比如中文、英文、数字等,我们经常使用的 JSON,他就是一种轻量级的数据交换格式。XML 相对来说那就是一个古老的存在,基本上都是在一些老式的程序中使用,都会从 XML 中读取数据,现在可以说是要被淘汰了,现在的程序几乎都是使用 JSON,因为同等数据量的情况下,XML 要比 JSON 大很多,这样会浪费带宽,浪费服务器资源,所以在使用 AJAX 获取从服务器返回的信息时,一般都使用 responseText 这个属性。

  7、请求状态监控

  XMLHttpRequest 对象的 readyState 属性返回请求的当前状态。当请求被发送到服务器时,我们需要执行一些基于响应的任务,每当 readyState 改变时,就会触发 onreadystatechange 事件,readyState 属性存有 XMLHttpRequest 的状态信息。

  XMLHttpRequest 对象的三个重要的属性:

    onreadystatechange:存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

   readyState:存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

      0:请求未初始化。还没有调用 open() 方法。

      1:服务器连接已建立,也就是载入。已调用 open() 方法,正在发送请求。

      2:请求已接收,载入完成。open() 方法完成,已收到全部响应内容。

      3:请求处理中,也叫解析。正在解析响应内容。

      4: 请求已完成,且响应已就绪。响应内容解析完成,可以在客户端调用了。

    status:请求结果,也就是 HTTP 状态码。200:OK。404:未找到页面。

  在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。

  当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

oAjax.onreadystatechange = function (){
if(oAjax.readyState == && oAjax.status == ){
alert(oAjax.responseText);
}
}

  这里要注意: onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。

  如果网站中存在多个 AJAX 任务,那么就可以使用回调函数,回调函数是一种以参数形式传递给另一个函数的函数,应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。

  该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-">
<title>AJAX 实例</title>
<script>
var oAjax;
function ajax(url, fnSucc){
oAjax = new XMLHttpRequest();
oAjax.onreadystatechange = fnSucc;
oAjax.open("GET", url, true);
oAjax.send();
}
function myFunction(){
ajax('ajax/demo.txt&#63;t=' + Math.random(), function (){ 
if(oAjax.readyState == && oAjax.status == ){ 
alert(oAjax.responseText); 
} 
}); 
} 
</script> 
</head> 
<body> 
<button type="button" onclick="myFunction()">读取</button> 
</body> 
</html>

  8、AJAX 原理

  AJAX 的原理就跟现实生活中给朋友打电话是一样一样的,首先,你得有个手机,不然拿什么打,也就是要有一个设备,当然现在那都是人手一部,这第一步就可以忽略了,然后就是拨号,所谓的拨号,就是把彼此的手机连接起来,建立一条通道,然后才能通信,如果接通了,就可以进行第三步了,那就是说,我们给别人打电话,肯定是要先说,然后再听对方说,那么最后就是听对方说,不可能是自己说完啪挂了,至少得听对方说点啥,也就是有个响应。

  打电话需要4个步骤完成,其实我们在编写 AJAX 时,也是需要4个步骤,首先,就得创建 AJAX 对象,有了这个对象之后,才能进行下面的操作,那么接下来要做的就是连接到服务器,就相当于打电话拨号,连接到服务器之后,你就得主动告诉服务器你需要什么文件,不可能是服务器丢给你几个文件,你自己选,要不是了再给你换一批,不可能这样,再说那服务器都是给成千上万人提供服务,不可能去跟你在那玩你猜我猜猜不猜,所以我们就得明确的告诉服务器我们要哪个文件,那么第三步就是发送请求,最后一步就是接收返回值,获得服务器的响应,也就是把我们需要的那个文件给我们传回来。

  我们平时都说 AJAX,其实这只是一个对外的称呼,真正在浏览器内部是通过 XMLHttpRequest 对象来完成 AJAX 请求的,这才是 AJAX 真正的对象。

  下面我们看一下,根据这4个步骤,AJAX 代码的具体编写过程:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-">
<title>AJAX 原理</title>
<script>
window.onload = function (){
var oBtn = document.getElementById('btn');
oBtn.onclick = function (){
// 、设备 = 创建 AJAX 对象
var oAjax = new XMLHttpRequest();
// 创建好对象之后,就可以弹出来看一下。返回:[object XMLHttpRequest]
// IE 和 IE 返回:[object]
//alert(oAjax);
// 在刚创建 AJAX 对象,还没调用 open() 方法,也就是请求未初始化时,弹出 readyState 状态。
//alert(oAjax.readyState); // 返回:
// 、拨号 = 连接服务器
oAjax.open('GET', 'ajax/demo.txt&#63;t=' + new Date().getTime(), true);
// 、说 = 发送请求
oAjax.send();
// 、听 = 接收返回
oAjax.onreadystatechange = function (){
// oAjax.readyState 浏览器和服务器进行到哪一步了
if(oAjax.readyState == ) // 请求已完成
if(oAjax.status == ){ // 成功
// 如果成功了,则弹出服务器响应的文本
alert('成功 ' + oAjax.responseText);
}
else{
// 如果失败了,则弹出请求结果。
alert('失败 ' + oAjax.status);
}
};
};
};
</script>
</head>
<body>
<button type="button" id="btn">读取</button>
</body>
</html>

  上面的代码,在进行最后一步时,判断浏览器和服务器进行到哪一步了,当 readyState 属性状态为4时,就是请求完成了,但是请求完成并不代表请求成功,如果读取出错了或者文件不存在等情况导致出错了,那么也算是请求完成了,也就是不管读取成功还是失败,都算是请求完成了,所以需要进一步使用 status 属性判断,若为200,就是成功了。使用自定义的个人站点打开上面的 demo,点击按钮后,弹出成功和文本中的内容,我们可以试着改变一下 URL,就是把他故意写错,再次点击按钮,则会弹出失败和404,也就是未找到页面。

  如果每次我们按照这4个步骤编写 AJAX 程序,是非常方便的,也容易理解,但是使用起来比较麻烦,所以我们可以把他封装为一个函数,在使用时调用就好使多了。

function ajax(url, fnSucc, fnFaild){
var oAjax = new XMLHttpRequest();
oAjax.open('GET', url, true);
oAjax.send();
oAjax.onreadystatechange = function(){
if(oAjax.readyState == ){
if(oAjax.status == ){
fnSucc(oAjax.responseText);
}
else{
if(fnFaild){
fnFaild(oAjax.status);
}
}
}
};
}

  上面封装的 ajax 函数有三个参数,第一个参数 url,是文件路径,第二个参数 fnSucc,当每次成功的时候调用函数,第三个参数 fnFaild,当失败时调用的函数。这里并不是任何情况下都需要失败时执行一个函数,所以需要做一个判断,只有当 fnFaild 这个参数传入进来,也就是定义了失败时执行的函数,那么这时候才去调用他。

  可以在 www 根目录中新建一个文件夹命名为 js,然后把上边的代码复制另存为 ajax.js,下面是封装好之后的应用:

<script src="js/ajax.js"></script>
<script>
window.onload = function (){
var oBtn = document.getElementById('btn');
oBtn.onclick = function (){
ajax('ajax/demo.txt&#63;t=' + new Date().getTime(), function (str){
alert('成功 ' + str);
}, function (){
alert('失败');
});
};
};
</script>

  我们要从服务器读取 demo.txt 这个文件,目的是为了获取这个文件中的内容,那么如何获取返回的结果呢?当成功的读取信息后,要调用 fnSucc 这个参数,也就是成功后执行的回调函数,他其实是有一个参数的 str,这个参数可以自定义,str 的作用就是把服务器返回给我们的内容传入进来,这个 str 参数就是 fnSucc(oAjax.responseText) 中传过来的。

  当失败的时候,调用 fnFaild 这个参数,也就是失败后执行的回调函数。那么这个失败时调用函数也是有一个参数的,fnFaild(oAjax.status),为了方便调试,我们也可以给他传入一个参数进来,用来提示请求失败的结果。在真正的网站中,当 AJAX 请求失败时,也不可能弹一个 alert,这样不太友好,所以可以自定义一些更加友好的方式来提示用户。这里建议大家平时在调试 AJAX 程序时,一定要加上失败时执行的回调函数,否则如果失败的话,那么可能没有任何反应。

  9、AJAX 应用

  请求一个静态的 TXT 文件,在了解了 AJAX 的原理后,很容易的就可以做到,但是在真正的网站中,这样不会有太大的实际用途,前边我们说 AJAX 是一种与服务器交换数据并更新部分网页的艺术,那么既然称之为艺术,因此我们需要使用 AJAX 去请求一些更实用、更复杂的东西,这样才能完美的体现他存在的价值。比如说我们可以去请求动态数据,例如去请求一个装着数据的 JSON 文件。

  (1)、读取数组

  首先,新建一个 TXT 文件命名为 arr.txt,随意存一个数组,比如[1,2,3,4,5,6],放在之前的 ajax 文件夹下,然后就可以开始编写程序了。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-">
<title>AJAX 读取数组</title>
<script src="js/ajax.js"></script>
<script>
window.onload = function (){
var oBtn = document.getElementById('btn');
oBtn.onclick = function (){
ajax('ajax/arr.txt&#63;t=' + new Date().getTime(), function (str){
// str 是服务器返回的内容,弹出来看一下
//alert(str); 返回:[,,,,,]
// 那么再弹出内容的长度
//alert(str.length); // 返回:
// 返回对象的类型:string
//alert(typeof str);
// eval() 函数用于把字符串转换为 JS 代码执行
//alert(eval(str)); // 返回:,,,,,
// 现在可以返回内容的长度
//alert(eval(str).length); // 返回:
// 可以把这个函数保存为变量,查看每项的值
var arr = eval(str);
alert(arr[]); // 返回:
}, function (){
alert('失败');
});
};
};
</script>
</head>
<body>
<button type="button" id="btn">读取</button>
</body>
</html>

  上面的实例中,str 是服务器返回给我们的内容,弹出来之后,是我们定义的数组,没有问题,那么弹出数组的长度,却返回 13,数组的长度本应该是 6 啊,怎么会是 13 呢,我们再弹出这个对象的类型,结果返回 string,尽管他长的很像数组,但他确实是一个字符串,这是为什么呢?其实通过 AJAX 的方式读取的任何对象都是以字符串形式存在的,那么这个字符串的长度就应该是13,方括号加上标点。如果要把一个字符串中存的数组提取出来,就要使用 eval(string) 函数,该函数可计算某个字符串,并把他作为 JavaScript 代码来执行,也就是可以把一个语句中的内容解析为 JS 可以识别的语句,该方法只接受原始字符串作为参数,如果 string 参数不是原始字符串,那么该方法将不作任何改变地返回。那么使用该方法之后再次返回数组的内容和长度,就没有问题了。我们也可以把这个函数保存在一个变量中,来查看每项的值。虽然 eval() 的功能非常强大,但在实际使用中用到他的情况并不多。

  (2)、读取 JSON 数据

  首先,还是需要新建一个 JSON 文件,可以命名为 json.json,可以随意存入一个数组对象,比如[{a:9, b:6, c:15}, {a:5, b:7, c:12}],然后放在 ajax 文件夹下,最后开始编写程序。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-">
<title>AJAX 读取数组</title>
<script src="js/ajax.js"></script>
<script>
window.onload = function (){
var oBtn = document.getElementById('btn');
oBtn.onclick = function (){
ajax('ajax/arr.txt&#63;t=' + new Date().getTime(), function (str){
// str 是服务器返回的内容,弹出来看一下
//alert(str); 返回:[,,,,,]
// 那么再弹出内容的长度
//alert(str.length); // 返回:
// 返回对象的类型:string
//alert(typeof str);
// eval() 函数用于把字符串转换为 JS 代码执行
//alert(eval(str)); // 返回:,,,,,
// 现在可以返回内容的长度
//alert(eval(str).length); // 返回:
// 可以把这个函数保存为变量,查看每项的值
var arr = eval(str);
alert(arr[]); // 返回:
}, function (){
alert('失败');
});
};
};
</script>
</head>
<body>
<button type="button" id="btn">读取</button>
</body>
</html>

  上面的实例,使用 eval() 函数解析出来之后,还是一个数组,返回数组的第0个元素,也就是{a:9, b:6, c:15},他还是一个 JSON 数据,所以返回 obj,那么再返回第0个元素中 a 的值,可以看到,使用方法和读取数组的方法是一样的。那如果 JSON 中保存的数据更复杂一些,比如是一组用户信息,要如何去读取,然后并以列表形式显示在网页中呢?

  下面是 JSON 用户信息数据,可以复制替换一下,这里在保存 JSON 时需要注意编码格式,一旦文件中出现中文了,就必须保存为 UTF-8 的格式,为了方便区分,我们可以把这个文件命名为 date.json 。

[
{
"user": "小白",
"sex": "男",
"age": 
},
{
"user": "初夏",
"sex": "女",
"age": 
},
{
"user": "小明",
"sex": "男",
"age": 
},
{
"user": "静静",
"sex": "女",
"age": 
}
]

  (3)、创建 DOM 元素显示 JSON 数据

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-">
<title>AJAX 读取JSON</title>
<script src="js/ajax.js"></script>
<script>
window.onload = function (){
var oBtn = document.getElementById('btn');
var oUl = document.getElementById('u');
oBtn.onclick = function (){
ajax('ajax/date.json&#63;t=' + new Date().getTime(), function (str){
var arr = eval(str);
//循环遍历返回的对象
for(var i=; i<arr.length; i++){
//每次循环的时候创建一个li元素
var oLi = document.createElement('li');
//向li元素插入内容
oLi.innerHTML = '姓名:<strong>' + arr[i].user + '</strong> 性别:<span>' + arr[i].sex + '</span> 年龄:<span>' + arr[i].age + '</span>';
//将创建好的li元素插入到ul中
oUl.appendChild(oLi);
}
  },function (){
  alert('失败');
});
};
};
</script>
</head>
<body>
<input id="btn" type="button" name="user" value="读取">
<!-- 点击按钮生成json数据列表 -->
<ul id="u">
<!-- <li>姓名:<strong>小白</strong> 性别:<span>男</span> 年龄:<span></span></li> -->
</ul>
</body>
</html>

  上面的代码,写起来也没什么难度,都是一些基础的知识,在浏览器打开自定义的个人站点,点击读取按钮之后,JSON 文件中存的数据,就会以为列表的形式显示在页面上,这里只是简单的做了一个效果,我们还可以给他定义样式,或者可以创建一个表格,让他更友好的显示。

  这里在网上看到了一个方法,在处理 AJAX 请求得到 JSON 数据响应时,也就是服务器返回的 JSON 字符串,需要做一次对象化处理,可以不使用 eval() 方法,而是使用 new Function() 代替,新的 Function() 构造就类似于 eval(),或者使用 jQuery 提供的 $.getJSON() 方法获得服务器返回,那么就可以不使用 eval() 方法了。具体操作如下:

//var arr = eval(str);
var arr = (new Function('', 'return' + str)()); 

  此时的 arr 就会被解析成一个 JSON 对象了,然后再使用循环遍历,将数据插入到新建的 li 元素中。

  10、AJAX 总结

  我们只是重点讲了一些 AJAX 最基础的知识,到这里,就可以使用 AJAX 做一些基本的应用了,但是 AJAX 不仅仅在于此,他有很多非常高级而且很实际的应用,比如一些大型系统如何使用 AJAX 搭建,如何编写一套完整的 AJAX 交互程序,还有跨域,还有JSONP等,要想真正的掌握 AJAX 这门艺术,我们的路还很长。

Statement:
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