2017-02-24 114 views
1

我正在使用JavaScript & Ajax使php调用从我的数据库返回数据。调用返回数据,因为它应该,但是当页面完全加载<div>标签值被清除。当页面完全加载时清除Div

我需要在我的语法中更改什么,以便div标记保留来自php文件的值echo?我检查了控制台,它只显示页面加载信息,没有任何与此问题相关的信息(至少不是我看到的)。

<form id="form1" method="post"> 
<div id="results">&nbsp;</div> 
<div style="padding-top: 10px;"><input type="submit" value="Submit" onclick="MakeQuery()" /></div> 
<script type="text/javascript"> 
var xhttp; 
function MakeQuery() 
{ 
if (window.XMLHttpRequest) {  
    xhttp = new XMLHttpRequest(); 
} else if (window.ActiveXObject) { 
    xhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
    xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4 && xhttp.status==200) 
    { document.getElementById("results").innerHTML = xhttp.responseText; } } 
    xhttp.open("GET", "SQLQuery.php", true); 
    xhttp.send(); 
} 
</script> 
</form> 
+0

是因为你忽略了,以防止实际的形式提交(去研究怎么做),所以浏览器提交表单并将来自服务器的响应显示为新文档。 – CBroe

+0

(或者,也可以不要使用_submit_按钮来首先触发脚本功能。) – CBroe

+0

我发现的所有内容都是我可以使用该按钮作为提交或重置。我不希望它被重置,似乎我也不希望它成为提交。 – BellHopByDayAmetuerCoderByNigh

回答

0

我认为你需要,以防止实际的形式使用AJAX之前提交:

var xhttp; 
 

 
function MakeQuery(event) { 
 
    event.preventDefault(); // Cancel form submit, use AJAX 
 

 
    if (window.XMLHttpRequest) { 
 

 
    xhttp = new XMLHttpRequest(); 
 
    } else if (window.ActiveXObject) { 
 
    xhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
 
    } 
 
    xhttp.onreadystatechange = function() { 
 
    if (xhttp.readyState == 4 && xhttp.status == 200) { 
 
     document.getElementById("results").innerHTML = xhttp.responseText; 
 
    } 
 
    } 
 
    xhttp.open("GET", "SQLQuery.php", true); 
 
    xhttp.send(); 
 
}

+0

这有效,但也使按钮突出显示。点击后有没有办法让按钮返回“正常”?直到我点击页面上的其他地方,它才会被突出显示。 – BellHopByDayAmetuerCoderByNigh

+1

@BellHopByDayAmetuerCoderByNigh是的,你模糊焦点的按钮就像这样document.getElementById(“buttonid”)。blur()。 或者您也可以将按钮“this”作为参数传递给它的使用模糊。 在此处阅读更多信息https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/blur – Riddell