【问题标题】:AJAX issue processing response data for display用于显示的 AJAX 问题处理响应数据
【发布时间】:2018-10-27 08:05:03
【问题描述】:

我目前正在做一个项目,并试图使用一些 AJAX 来使提交一些较小的表单更加顺畅。我尝试通过获取“提交”按钮来仅在其下方的段落中显示 .txt 文件中的文本来对其进行测试,但这不起作用...

这是我的代码:

<div style="color: #818181; width: auto; height 50vh; display:flex; flex-direction: row; justify-content: space-around;">

<div style="padding: 2vw; width: 35vw; height: 50vh; display: flex; justify-content: top; flex-direction: column; ">
<h2 style="color: #818181; margin: 0;">Contact</h2>
Questions? Go ahead.
<form method="post">
<p><input name='lcontactname' type="text" placeholder="Name" style="height: 5vh; width:28vw" required></p>
<p><input name='lcontactemail' type="text" placeholder="Email" style="height: 5vh; width:28vw" required></p>
<p><input name='lcontactsubject' type="text" placeholder="Subject" style="height: 5vh; width:28vw" required></p>
<p><input name='lcontactmessage' type="text" placeholder="Message" style="height: 5vh; width:28vw" required></p>
<p><input onClick='submitlContact' type='button' value='send' style="height: 5vh; width: 28vw; color: white;background-color:black; border: 2px white; padding: auto; font-size: calc(1vw + 0.5vh);" onClick='lcontactSend();'></p>
<p id='testpar'></p>
</form>
</div>

<script>
function submitlContact(){ //AJAX TO SUBMIT THIS FORM
    //if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
    //} else {
    // code for IE6, IE5
   // xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    //}
    xhttp.open("GET", "lcontactsubmit.txt", true);
    xhttp.send();
    document.getElementById("testpar").innerHTML = xhttp.responseText;

}   



</script>

这个想法是,当按下按钮时,我可以看到 .txt 文件的内容,该文件中有一个名为 lcontactsubmit.txt 的随机单词,并且肯定会保存为包含随机乱七八糟的字母。

有什么建议吗?

:)

【问题讨论】:

  • 嗨,所以您希望在单击send button 后将来自lcontactsubmit.txt 的文本打印在&lt;p id='testpar'&gt;&lt;/p&gt; 中?

标签: javascript php html css ajax


【解决方案1】:

您必须先等待响应,xhttp.responseText 在您发送请求后不会立即可用,要使用一些事件,例如 onreadystatechange

喜欢:

xhttp = new XMLHttpRequest();
xhttp.open("GET", "lcontactsubmit.txt", true);
xhttp.onreadystatechange = function() {
    if (this.readyState==4 && this.status==200) {
        document.getElementById("testpar").innerHTML = this.responseText;
    }
}
xhttp.send();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2011-12-05
    • 2011-11-04
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多