我在HTML / javascript脚本中创建了两个简单的ajax调用。他们调用一个只返回一个简单字符串的php例程。该字符串将被替换为HTML文本行。它们工作正常,但HTML页面似乎刷新并消除刚刚插入的文本。我已经尝试了xhttp.open的同步和异步版本。我有警报,以便您可以测试它。
如何更改文字"坚持"这样它就不会被覆盖。感谢。
<!DOCTYPE HTML>
<html>
<body>
<h1>AJAX Tester</h1>
<p>Echo here from the server: <span id="text">replace here</span></p>
<form onclick="localform()">
<button type="submit" >Submit</button>
</form>
<p>Echo here from the server: <span id="text1">replace here</span></p>
<form onclick="localform1()">
<button type="submit" >Submit</button>
</form>
<script>
function localform() {
//This routine checks the ajax with a synchronous (call "false" in the open)
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxtester.php",false);
xhttp.send();
document.getElementById("text").innerHTML = xhttp.responseText;
alert("Test1"+xhttp.responseText) ;
return
}
function localform1() {
//This routine checks the ajax with an asynchronous (call "true" in the open)
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("text1").innerHTML = xhttp.responseText;
alert("Test5"+xhttp.responseText) ;
}
};
xhttp.open("GET", "ajaxtester.php", true);
xhttp.send();
alert("Test4"+xhttp.responseText) ;
return
}
</script>
</body>
</html>
&#13;
php代码非常简单:
<?php
echo "we made it";
?>
感谢您的帮助。对于我在前两个问题中犯的错误感到抱歉,我在这里是一个菜鸟,只是在学习绳索。
答案 0 :(得分:0)
要在html页面中直接插入js函数调用,我建议您添加稍后需要的相应参数:
单击按钮,在您需要停止或阻止默认行为的功能中,否则页面将被提交,这是您不想要的。
在下面的代码中,我将all减少到只有一个函数:
function localform(currEle, evt, urlStr, objId) {
var e = evt || window.event;
e.preventDefault();
var xAjax = null;
if (XMLHttpRequest) {
xAjax = new XMLHttpRequest();
} else {
xAjax = new ActiveXObject("Microsoft.XMLHTTP");
}
xAjax.open("GET", urlStr, true);
xAjax.onreadystatechange = function(){
if(xAjax.readyState == 4 && xAjax.status == 200){
document.getElementById(objId).innerHTML = xAjax.responseText;
alert("Test1"+xhttp.responseText)
}
}
xAjax.send();
}
<h1>AJAX Tester</h1>
<p>Echo here from the server: <span id="text">replace here</span></p>
<form onclick="localform(this, event, 'ajaxtester.php', 'text')">
<button type="submit" >Submit</button>
</form>
<p>Echo here from the server: <span id="text1">replace here</span></p>
<form onclick="localform(this, event, 'ajaxtester.php' 'text1')">
<button type="submit" >Submit</button>
</form>