Ajax与YUI框架:高效开发指南(上)
立即解锁
发布时间: 2025-08-19 00:23:15 阅读量: 1 订阅数: 4 


PHP、MySQL和JavaScript学习指南
### Ajax与YUI框架:高效开发指南(上)
#### 1. Ajax请求基础
在进行Ajax请求时,`readyState`属性有五个不同的值,但我们主要关注值为4的情况,它代表一个完成的Ajax调用。每次新函数被调用时,在`readyState`值为4之前,函数不做任何操作直接返回。当检测到`readyState`值为4时,会检查请求的`status`状态,若状态值为200,表示请求成功;若不是200,则弹出包含`statusText`错误信息的警告框。
以下是相关代码示例:
```javascript
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
document.getElementById('info').innerHTML = this.responseText;
} else {
alert("Ajax error: No data received");
}
} else {
alert("Ajax error: " + this.statusText);
}
}
}
```
在上述代码中,使用`this`关键字引用对象属性,这样代码可以方便地复制粘贴,并且适用于任何对象名称,因为`this`关键字始终指向当前对象。
#### 2. 服务器端处理(PHP部分)
以`urlpost.php`为例,它接收POST请求中的`url`参数,并使用`file_get_contents`函数加载该URL对应的网页内容。同时,使用`SanitizeString`函数对输入数据进行清理,以防止潜在的安全问题。
```php
<?php // urlpost.php
if (isset($_POST['url'])) {
echo file_get_contents("http://".SanitizeString($_POST['url']));
}
function SanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
```
#### 3. 使用GET请求替代POST请求
提交表单数据时,可以选择使用GET请求,这样可以节省一些代码。但部分浏览器可能会缓存GET请求,而POST请求不会被缓存。为避免缓存问题,可以在每个请求中添加一个随机参数,确保每个请求的URL都是唯一的。
以下是`urlget.html`和`urlget.php`的示例代码:
`urlget.html`:
```html
<html>
<head>
<title>Ajax GET Example</title>
</head>
<body>
<center />
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
nocache = "&nocache=" + Math.random() * 1000000;
request = new ajaxRequest();
request.open("GET", "urlget.php?url=oreilly.com" + nocache, true);
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
document.getElementById('info').innerHTML = this.responseText;
} else {
alert("Ajax error: No data received");
}
} else {
alert("Ajax error: " + this.statusText);
}
}
}
request.send(null);
function ajaxRequest() {
try {
var request = new XMLHttpRequest();
} catch (e1) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e2) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e3) {
request = false;
}
}
}
return request;
}
<
```
0
0
复制全文
相关推荐










