JavaScript之使用AJAX(适合初学者)

  网上关于AJAX的教程和分享层出不穷,现实生活中关于AJAX的书籍也是琳琅满目,然而太多的选择容易令人眼花缭乱,不好取舍。事实是,一般的教程或书籍都不会讲Web服务器的搭建,因此,对于初学者(比如笔者)来说,好不容易学习了AJAX的知识,却还是没有办法亲身实践操作一把,这是多大的遗憾啊!
  所以这一次,笔者将会举一个简单的AJAX应用实例,来详细地讲述如何在本地电脑上使用AJAX来满足Web开发要求。
  首先,我们需要在自己的电脑上安装好XAMPP,这是为了开启Apache服务器,这样就不需要我们自己再去搭建服务器。XAMPP的下载地址为:https://www.apachefriends.org/zh_cn/index.html .
  下载完后直接安装即可。笔者下载的Window版本,安装完后,打开XAMPP Control Panel,点击“Apache”前面的按钮来安装Apache服务,并点击“Apache”后面的start按钮以开启Apache服务,如下图所示:

开启Apache服务

Apache的默认端口应为443,笔者因为该端口已被占用,故改为4431.
  接着我们在XAMPP的安装目录下的htdocs的文件夹下分别新建一个HTML文件:programming_language_intro.html和PHP文件:intro.php,如下如所示:

新建文件

  其中programming_language_intro.html的代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function showIntro(){
    //所有现代浏览器均支持XMLHttpRequest对象(IE5和IE6使用ActiveXObject)
    //XMLHttpRequest用于在后台与服务器交换数据
    var xmlhttp = new XMLHttpRequest();
    var str = document.getElementById("language").value;
    
    //onreadystatechange:存储函数(或函数名),每当readyState属性改变时,就会调用该函数
    //readyState:4表示请求已完成,且响应已就绪
    //status:200表示"OK"
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("p1").innerHTML = "Introduction of "+str+":";
            //获取来自服务器的响应:responseText表示获得字符串形式的响应数据
            document.getElementById("intro").innerHTML = xmlhttp.responseText;
        }
    }
    //将请求发送到服务器
    //open()的三个参数分别为:GET请求或POST请求,url:服务器上的文件,异步:是或否
    xmlhttp.open("GET","intro.php?query="+str,true);
    xmlhttp.send();
}

//刷新页面
function refresh_page(){
    location.reload();
}
</script>
</head>
<body>

<h3>Programming Language Introduction</h3>
<form action=""> 
    Language: 
    <select id='language'>
        <option>C</option>
        <option>HTML</option>
        <option>Java</option>
        <option>JavaScript</option>
        <option>PHP</option>
        <option>Python</option>
        <option>R</option>
        <option>Scala</option>
    </select>
</form>
<br>
<button onclick="showIntro()">SHOW</button>
<button onclick="refresh_page()">REFRESH</button>
<p id='p1'>Introduction: </p> 
<p><span id="intro"></span></p>

</body>
</html>

在showIntro()中使用了AJAX,关于AJAX的具体教程可以参考:http://www.runoob.com/ajax/ajax-tutorial.html .
  intro.php的代码如下:(PHP语言)

<?php
//$intro:Associative Array, keys are programming languages
$intro = array();

$intro["C"] = "C is a general-purpose, imperative computer programming language, supporting structured programming,  lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, and therefore  it has found lasting use in applications that had formerly been coded in assembly language, including operating systems, as well as various application software for computers ranging from supercomputers to embedded systems.";
                    
$intro["HTML"] = "Hypertext Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS) and JavaScript it forms a triad of cornerstone technologies for the World Wide Web. Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.";

$intro["Java"] = "Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented,[15] and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers 'write once, run anywhere' (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM)regardless of computer architecture. As of 2016, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers. Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.";

$intro["JavaScript"] = "JavaScript often abbreviated as JS, is a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language. Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production. It is used to make webpages interactive and provide online programs, including video games. The majority of websitesemploy it, and all modern web browsers support it without the need for plug-ins by means of a built-in JavaScript engine. Each of the many JavaScript engines represent a different implementationof JavaScript, all based on the ECMAScript specification, with some engines not supporting the spec fully, and with many engines supporting additional features beyond ECMA.";
                    
$intro["PHP"] = "PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Group. PHP originally stood for Personal Home Page, but it now stands for the recursive backronym PHP: Hypertext Preprocessor";
                 
$intro["Python"] = "Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossumand first released in 1991, Python has a design philosophy that emphasizes code readability, and a syntax that allows programmers to express concepts in fewer lines of code, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.";
                    
$intro["R"] = "R is a free (libre) programming language and software environment for statistical computing and graphics that is supportedby the R Foundation for Statistical Computing. The R language is widely used among statisticians and data miners for developing statistical software and data analysis. Polls, surveys of data miners, and studies of scholarly literature databases show that R's popularity has increased substantially in recent years. R ranks 8th in the TIOBE index.";
               
$intro["Scala"] = "Scala is a general-purpose programming language providing support for functional programming and a strong static type system.Designed to be concise, many of Scala's design decisions aimed to address criticisms of Java.";
                   
//get the query parameter from URL
$query = $_GET["query"];
echo $intro[$query];
?>

  在浏览器中输入http://localhost/programming_language_intro.html ,得到的页面如下:

programming_language_intro.html

  在下拉菜单中选择"JavaScript",则页面如下:

JavaScript介绍

  在下拉菜单中选择"Python",则页面如下:

Python介绍

  笔者的学习心得:有时候光看网上或书上的教程,是远远不够的,因为可能并没有讲如何具体地操作实践,最好的学习方法还是自己亲自实践一把,然后写个Blog记录之~~
  本次分享到此结束,欢迎大家交流~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342