首页 » 科技 » 简单的Ajax实例

简单的Ajax实例

Ajax 是一种可以通过Javascript, DHTML and the XMLHttpRequest 来发送GET或POST请求,在数据返回时不必重新载入页面。下面是一个非常简单的Ajax例子,发送一个请求,打印出请求的字符串和远程用户的IP地址。

Tags:AJAX | c | cgi

简单的Ajax实例

Ajax 是一种可以通过Javascript, DHTML and the XMLHttpRequest 来发送GET或POST请求,在数据返回时不必重新载入页面。 下面是一个非常简单的Ajax例子,发送一个请求,打印出请求的字符串和远程用户的IP地址。

简单的Ajax演示 (请参考原文演示: http://www.degraeve.com/reference/simple-ajax-example.php)

Html 页面

这个HTML页面提供了3个JavaScript函数,通过执行XMLHttpRequest来更新HTML页面.(AJAX调用)

<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}

function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/simple-ajax-example.cgi")'></p>
<div id="result"></div>
</form>
</body>
</html>

CGI 脚本

这个CGI脚本是用来应答HTML页面的JavaScript的请求。 CGI脚本可以通过简单的Python, Puby, PHP, C, Perl 等来实现。


#!/usr/bin/perl -w
use CGI;

$query = new CGI;

$secretword = $query->param('w');
$remotehost = $query->remote_host();

print $query->header;
print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>

【本文翻译仅为外语学习及阅读目的,原文作者个人观点与译者及译言网无关】

10

返回正文评论