另一种风格的ajax调用
Another style of ajax call
我正在做一些纯Javascript的AJAX调用实验,没有JQuery。我想知道我是否可以像这样填充一个DIV标签:
<script type="text/javascript">
function call_test() {
document.getElementById("myId").innerHTML = ajax_call("example.php?id=1") ;
}
</script>
<body>
<input type="button" onClick="call_test()" value"Test">
<div id="myId">Result should be here</div>
问题是如何从ajax_call返回结果?我的代码如下,但不工作:
function ajax_call(remote_file)
{
var $http,
$self = arguments.callee ;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function() {
if (/4|^complete$/.test($http.readyState)) {
return http.responseText ; // This only return undefined
}
};
$http.open('GET', remote_file , true);
$http.send(null);
}
}
远程文件:<?php
echo "<h1>Jus an experiment</h1>";
?>
由于AJAX请求的异步特性,它将不起作用。ajax_call
方法将在服务器响应html之前返回,这就是您获得undefied
的原因。
这里的解决方案是使用回调来完成ajax响应的后处理,如下所示。
function ajax_call(remote_file, callback) {
var $http, $self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function() {
if (/4|^complete$/.test($http.readyState)) {
if (callback)
callback(http.responseText);
}
};
$http.open('GET', remote_file, true);
$http.send(null);
}
}
和
function call_test() {
ajax_call("example.php?id=1", function(html) {
document.getElementById("myId").innerHTML = html
});
}
相关文章:
- 阻止在select2单击时调用ajax
- 调用Ajax并返回响应
- Ajax:只在元素存在的情况下调用Ajax
- PHP,MySQL,AJAX-调用AJAX结果后,Bootstrap CSS样式不会显示
- 调用Ajax内部的函数
- 无法获取属性'的值;拆分'在IE8中调用ajax之后
- 我们如何在Firefox中调用AJAX
- Rails:通过调用Ajax重定向
- Cookie 在 Spotify (Javascript) 中调用 ajax 后未保存
- 通过调用 Ajax 来设置 struts bean 值
- 无法从服务器中的 php 调用 Ajax 函数
- 如何在附加表行时调用 ajax
- 在facebook用户发送邀请请求后调用ajax调用
- 定期调用Ajax
- 调用Ajax生成的表单的值
- 无法调用ajax函数
- 在调用AJAX之后显示ng控制器的内容;作为“;作用
- CSS,Java脚本在php中调用ajax后无法正常工作
- 成功调用AJAX后,Toast Growl不会出现
- 如何在调用AJAX时记录或捕获信息和错误