我一直在尝试在我的网络应用程序中使用AJAX来加快速度。我有两个文件,readdata.php,其中包含html和ajax请求,以及data.php,它回显我需要异步更新的文本信息。
以下是两个文件:
readdata.php
<!DOCTYPE html>
<html>
<head>
<title>Read Data</title>
<?php
//these two posts are required to access the database and are passed through a submit button from index.php
$rName=$_POST["registration"];
$rowId=$_POST["rowid"];
?>
<script>
function showUser(str) { //mostly copied from online ajax tutorial
if (str=="") {
document.getElementById("txtHint").innerHTML==xmlhttp.responseText;
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","data.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
</script>
</head>
<body>
<br>
<div id="txtHint"><b>data.php text will be listed here.</b></div>
</body>
</html>
和另一个:
data.php
<?php
echo "Hello World"; //this is the text that I want to be displayed and asynchronously updated.
?>
</body>
</html>
当我转到index.php并点击链接到readdata.php的按钮时,只会在此处列出文本“data.php文本”。被展示。任何帮助将不胜感激。
答案 0 :(得分:0)
好吧,
我会尽量让它变得容易。
我总是建议使用jQuery(如果是这样,请包含最新的API或将其放在主机上)
$.ajax({
type: "POST", //Or even get
url: "read.php",
data: {
//Theese are the variables and their relative values
name: "Brad",
surname: "Pitt"
}
})
.done(function( msg ) {
alert( "Result: " + msg );
});
无论将从read.php回复什么,都将显示在警报上。您可以通过将此脚本置于function() {}
之内来调用此脚本:
function syncWithAjax() {
$.ajax({
type: "POST",
url: "read.php",
data: {
name: "Brad",
surname: "Pitt"
}
})
.done(function( msg ) {
alert( "Result: " + msg );
});
}