为什么Ajax和PHP脚本不张贴回原来的形式脚本、形式、Ajax、PHP

2023-09-10 14:49:39 作者:挥霍不该挥霍的挥霍

我有这样的形式和我使用AJAX将数据发送到一个简单的PHP脚本(只是解决问题用简单的PHP脚本),但它没有回发数据为原始的HTML表单......这里有两个脚本 contact.html

 <!DOCTYPE HTML>
< HTML LANG =EN>
  < HEAD>
    <元字符集=utf-8>
    < META HTTP-当量=X-UA-Compatible的内容=IE =边缘>
    < META NAME =视口内容=WIDTH =装置宽度,初始规模= 1>
    <! - 上面的3元标记*必须*先来的头部;任何其他头的内容必须经过来* *这些标签 - >
    <冠军>联系我们< /标题>

    <! - 引导 - >
    <链接HREF =bootstrap.min.css相对=样式>
    <! - 样式表这种形式 - >
    <链接HREF =接触stylesheet.css中相对=样式>

    <! -  HTML5垫片和Respond.js对IE8的支持HTML5元素和媒体查询 - >
    !<  - 警告:Respond.js不,如果你通过文件浏览网页的工作://  - >
    <! -  [如果其中IE 9] GT;
      &所述;脚本的src =htt​​ps://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js>&所述; /脚本>
      &所述;脚本的src =htt​​ps://oss.maxcdn.com/respond/1.4.2/respond.min.js>&所述; /脚本>
    百分比抑制率ENDIF]  -  GT!;
    <脚本类型=文/ JavaScript的>
        功能validateForm()
        {
            VAR消息=;
            无功字母= / ^ [A-ZA-Z] + $ /;
            //做验证
            。VAR jname = document.forms [myForm会] [名称]值;
            。VAR jemail = document.forms [myForm会] [电子邮件]值;
            。VAR jsubject = document.forms [myForm会] [主题]值;
            。VAR jtext = document.forms [myForm会] [文字]值;
            VAR joutputMsg =;

            //检查空字段
            如果(jname == NULL || jname ==){
                消息+ =!名字字段为空\ N的;
            }
            如果(jname =&放大器;!&安培;!jname.match(字母)){
                消息+ =无效的名称:!只有字母允许\ N的;
            }
            如果(jemail == NULL || jemail ==){
                消息+ =电子邮件字段为空\ N!;
            }
            如果(jsubject == NULL || jsubject ==){
                消息+ =主题字段为空\ N!;
            }
            如果(jtext == NULL || jtext ==){
                消息+ =文本字段为空\ N!;
            }

            如果(消息!=){
                警报(消息);
                返回false;
            }

            //将数据发送到PHP的形式--------------------->
            //创建XMLHtt prequest目的,根据浏览器
            //创建一个包含XMLHtt prequest对象(最初用空值)的实例变量
            VAR XMLHTTP = NULL;

            如果(window.XMLHtt prequest){//为Forefox,IE7 +,歌剧,Safari浏览器,...
            XMLHTTP =新XMLHtt prequest();
            }
            否则,如果(window.ActiveXObject){//用于Internet Explorer 5或6
            XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
            }

            //将数据发送到PHP文件,通过自检,并显示所接收到的答案
            //创建对指数=值与数据必须被发送到服务器
            VAR参数=NAME =+ jname +&放大器;电子邮件=+ jemail;

            request.open(POST,contact.php,真正的); //设置请求

            //添加标题,告诉PHP脚本识别数据是通过POST发送
            request.setRequestHeader(内容型,应用程序/ x-WWW的形式urlen codeD);
            request.send(the_data); //调用send()方法DATAS作为参数

            //检查请求的状态
            //如果响应被完全接收,将被转移到与TAGID HTML标记
            request.onreadystatechange =功能(){
                如果(request.readyState == 4){
                  的document.getElementById(输出数据)的innerHTML = request.responseText。
                }
            }
            返回false;
        }

    < / SCRIPT>
  < /头>
  <身体GT;

      < D​​IV CLASS =行>
          < D​​IV CLASS =英雄单位的风格=填充:20像素100像素>
            < H1>联系我们< / H1>
            &其中p为H.; aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd&所述; / P>
        < / DIV>
          < D​​IV CLASS =COL-SM-6>
            < D​​IV CLASS =我型>
                <窗​​体类=形横NAME =myForm的行动=contact.php的onsubmit =返回validateForm(事件)方法=邮报>
          < D​​IV CLASS =形组>
            <标签=inputEmail3级=COL-SM-2控制标签>名称:< /标签>
            < D​​IV CLASS =COL-SM-8>
              <输入类型=名的名称=名称级=表单控制ID =inputEmail3占位符=名称>
            < / DIV>
          < / DIV>
          < D​​IV CLASS =形组>
            <标签=inputPassword3级=COL-SM-2控制标签>电子邮件:LT; /标签>
            < D​​IV CLASS =COL-SM-8>
              <输入类型=电子邮件NAME =电子邮件级=表单控制ID =inputPassword3占位符=电子邮件>
            < / DIV>
          < / DIV>
          < D​​IV CLASS =形组>
            <标签=inputPassword3级=COL-SM-2控制标签>主题:< /标签>
            < D​​IV CLASS =COL-SM-8>
              <输入类型=文本名称=主题类=表单控制占位符=主题>
            < / DIV>
          < / DIV>

          < D​​IV CLASS =形组>
              <标签=inputPassword3级=COL-SM-2控制标签>文字:LT; /标签>
              < D​​IV CLASS =COL-SM-8>
                < textarea的名字=文本级=表单控制行=7占位符=文本>< / textarea的>
              < / DIV>
          < / DIV>
          < D​​IV CLASS =形组>
            < D​​IV CLASS =COL-SM-偏移2 COL-SM-10>
              <按钮类型=提交级=BTN BTN默认>发送和LT; /按钮>
            < / DIV>
          < / DIV>
            < / DIV>
        < /形式GT;
          < / DIV>
          < D​​IV CLASS =COL-SM-6>
              < D​​IV的风格=宽度:500px的; heigth:350像素;边框:1px的固体棕色>
                < H1> GOOGLE MAP此处<!/ H1>
              < / DIV>
             !<  - < IMG sytle =填充:0px 20px的 src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL"> - >
          < / DIV>
      < / DIV>
      < D​​IV CLASS =COL-SM-6ID =MSG-结果的风格=填充:10px的140px>
              &其中,P ID =输出数据>

              &所述; / P>
            <  - !在这里展示的形式结果的消息! - >
      < / DIV>


    <! -  jQuery的(必要引导的JavaScript插件) - >
    &所述;脚本的src =htt​​ps://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js>&所述; /脚本>
    <! - 包括所有编译插件(下图),或者包括个人所需文件 - >
    <脚本SRC =JS / bootstrap.min.js>< / SCRIPT>

  < /身体GT;
< / HTML>
 

contact.php

 < PHP

    如果(使用isset($ _ POST ['名称'])){
        $名称= $ _ POST ['名称'];

    }

    如果(使用isset($ _ POST [电子邮件])){
        $电子邮件= $ _ POST [电子邮件];
    }

    回声名称:。 $名字。 < BR>电子邮件:。 $电子邮件;
?>
 

解决方案

有这么多的错误,但我有它的工作,你可能想看看您的输入域的命名约定。例如上的名称的你有 ID =inputEmail13的ID。使用浏览器控制台看到错误消息,因为你开发。

 函数validateForm(事件)
{
    。事件preventDefault();
    VAR消息=;
    无功字母= / ^ [A-ZA-Z] + $ /;
    //做验证
    。VAR名称= document.forms [myForm会] [名称]值;
    。VAR电子邮件= document.forms [myForm会] [电子邮件]值;
    。无功受= document.forms [myForm会] [主题]值;
    VAR文本= document.forms [myForm会] [文字]值。
    VAR outputMsg =;

    //检查空字段
    如果(名称== NULL ||名==){
        消息+ =!名字字段为空\ N的;
    }
    如果(名称=&放大器;!&安培;!name.match(字母)){
        消息+ =无效的名称:!只有字母允许\ N的;
    }
    如果(电子邮件== NULL ||电子邮件==){
        消息+ =电子邮件字段为空\ N!;
    }
    如果(主题== NULL ||主题==){
        消息+ =主题字段为空\ N!;
    }
    如果(文字== NULL ||文本==){
        消息+ =文本字段为空\ N!;
    }

    如果(消息!=){
        警报(消息);
        返回false;
    }

    //将数据发送到PHP的形式--------------------->
    //创建XMLHtt prequest目的,根据浏览器
    //创建一个包含XMLHtt prequest对象(最初用空值)的实例变量
    VAR XMLHTTP = NULL;

    如果(window.XMLHtt prequest){//为Forefox,IE7 +,歌剧,Safari浏览器,...
    XMLHTTP =新XMLHtt prequest();
    }
    否则,如果(window.ActiveXObject){//用于Internet Explorer 5或6
    XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
    }

    //将数据发送到PHP文件,通过自检,并显示所接收到的答案
    //创建对指数=值与数据必须被发送到服务器
    VAR参数=NAME =+姓名+&放大器;电子邮件=+电子邮件;

    xmlHttp.open(POST,contact.php,真正的); //设置请求

    //添加标题,告诉PHP脚本识别数据是通过POST发送
    xmlHttp.setRequestHeader(内容型,应用程序/ x-WWW的形式urlen codeD);
    xmlHttp.send(参数); //调用send()方法DATAS作为参数

    //检查请求的状态
    //如果响应被完全接收,将被转移到与TAGID HTML标记
    xmlHttp.onreadystatechange =功能(){
        如果(xmlHttp.readyState == 4){
          的document.getElementById(输出数据)的innerHTML = xmlHttp.responseText。
        }
    }
    返回false;
}
 
minishowcase

在HTML要删除可见性:隐藏; 在输出的div

 < D​​IV CLASS =COL-SM-6ID =MSG-结果的风格=填充:10px的140px;>
      &其中,P ID =输出数据>
      &所述; / P>
    <  - !在这里展示的形式结果的消息! - >
< / DIV>
 

编辑:

未定义请求的原因是因为你从来没有创建一个名为请求变量,但你打电话的。

  request.open(POST,contact.php,真正的);
 

这行会抛出的第一个错误说这是不确定的,这可以很容易地通过改变固定要求 XMLHTTP 或修改 XMLHTTP =新XMLHtt prequest(); 要求=新...... 同样要做其他XMLHTTP分配。

I have this form and I'm using ajax to send data to a simple php script (just trouble shooting with simple php script) but it is not posting back data to original html form... here are the two scripts contact.html

   <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Contact Us</title>

    <!-- Bootstrap -->
    <link href="bootstrap.min.css" rel="stylesheet">
    <!-- stylesheet for this form -->
    <link href="contact-stylesheet.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript">
        function validateForm()
        {
            var message = "";
            var letters = /^[A-Za-z]+$/;    
            //do validation
            var jname = document.forms["myForm"]["name"].value;
            var jemail = document.forms["myForm"]["email"].value;
            var jsubject = document.forms["myForm"]["subject"].value;
            var jtext = document.forms["myForm"]["text"].value;
            var joutputMsg = "";

            //checking for empty fields
            if (jname == null || jname == "") {             
                message += "name field empty!\n";
            }               
            if (jname != "" && !jname.match(letters)) {
                message += "Invalid name: only letters allowed!\n";
            }
            if (jemail == null || jemail == "") {
                message += "email field is empty!\n";
            }
            if (jsubject == null || jsubject == "") {
                message += "Subject field is empty!\n";
            }
            if (jtext == null || jtext == "") {
                message += "Text field is empty!\n";
            }           

            if (message != "" ) {
                alert(message);
                return false;
            }

            //send data to php form--------------------->
            // create the XMLHttpRequest object, according browser          
            // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
            var xmlHttp = null;

            if(window.XMLHttpRequest) {     // for Forefox, IE7+, Opera, Safari, ...
            xmlHttp = new XMLHttpRequest();
            }
            else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            // sends data to a php file, via POST, and displays the received answer         
            // create pairs index=value with data that must be sent to server
            var parameters="name="+jname+"&email="+jemail;

            request.open("POST", "contact.php", true);          // set the request

            // adds  a header to tell the PHP script to recognize the data as is sent via POST
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.send(the_data);     // calls the send() method with datas as parameter

            // Check request status
            // If the response is received completely, will be transferred to the HTML tag with tagID
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                  document.getElementById("output-data").innerHTML = request.responseText;
                }
            }           
            return false;
        }       

    </script>
  </head>
  <body>

      <div class="row">
          <div class="hero-unit" style="padding:20px 100px">
            <h1>Contact Us</h1>
            <p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>       
        </div>
          <div class="col-sm-6">
            <div class="my-form">
                <form class="form-horizontal" name="myForm" action="contact.php" onsubmit="return validateForm(event)" method="post">
          <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
            <div class="col-sm-8">
              <input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
            </div>
          </div>
          <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
            <div class="col-sm-8">
              <input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
            </div>
          </div>
          <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
            <div class="col-sm-8">
              <input type="text" name="subject" class="form-control" placeholder="Subject">
            </div>
          </div>

          <div class="form-group">
              <label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
              <div class="col-sm-8">
                <textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
              </div>    
          </div>
          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button type="submit" class="btn btn-default">Send</button>
            </div>
          </div>    
            </div> 
        </form>
          </div>
          <div class="col-sm-6">
              <div style="width:500px;heigth:350px;border:solid 1px brown">
                <h1>GOOGLE MAP HERE!</h1>
              </div>
             <!-- <img sytle="padding:0px 20px" src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL">                     -->
          </div>      
      </div>
      <div class="col-sm-6" id="msg-result" style="padding:10px 140px">
              <p id="output-data">

              </p>
            <!-- display form result message here! -->
      </div>


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>

  </body>
</html>

contact.php

<?php

    if (isset($_POST['name'])) {
        $name = $_POST['name'];                  

    }

    if (isset($_POST['email'])) {
        $email = $_POST['email'];
    }

    echo "Name: " . $name . "<br> Email: " . $email;    
?>

解决方案

There is so many errors but I've got it working, you might want to look at the naming convention on your input fields. For example on name you have the id of id="inputEmail13". Use the browser console to see error messages as you're developing.

function validateForm(event)
{
    event.preventDefault();
    var message = "";
    var letters = /^[A-Za-z]+$/;    
    //do validation
    var name = document.forms["myForm"]["name"].value;
    var email = document.forms["myForm"]["email"].value;
    var subject = document.forms["myForm"]["subject"].value;
    var text = document.forms["myForm"]["text"].value;
    var outputMsg = "";

    //checking for empty fields
    if (name == null || name == "") {               
        message += "name field empty!\n";
    }               
    if (name != "" && !name.match(letters)) {
        message += "Invalid name: only letters allowed!\n";
    }
    if (email == null || email == "") {
        message += "email field is empty!\n";
    }
    if (subject == null || subject == "") {
        message += "Subject field is empty!\n";
    }
    if (text == null || text == "") {
        message += "Text field is empty!\n";
    }           

    if (message != "" ) {
        alert(message);
        return false;
    }

    //send data to php form--------------------->
    // create the XMLHttpRequest object, according browser          
    // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    var xmlHttp = null;

    if(window.XMLHttpRequest) {     // for Forefox, IE7+, Opera, Safari, ...
    xmlHttp = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // sends data to a php file, via POST, and displays the received answer         
    // create pairs index=value with data that must be sent to server
    var parameters="name="+name+"&email="+email;

    xmlHttp.open("POST", "contact.php", true);            // set the request

    // adds  a header to tell the PHP script to recognize the data as is sent via POST
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.send(parameters);     // calls the send() method with datas as parameter

    // Check request status
    // If the response is received completely, will be transferred to the HTML tag with tagID
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
          document.getElementById("output-data").innerHTML = xmlHttp.responseText;
        }
    }           
    return false;
}    

In the html you want to remove the visibility:hidden; on the output div

<div class="col-sm-6" id="msg-result" style="padding:10px 140px;">
      <p id="output-data">
      </p>
    <!-- display form result message here! -->
</div>

Edit:

Cause of the request is undefined is because you're never creating a variable called request, yet you're calling one.

request.open("POST", "contact.php", true);

This line will throw the first error saying it's undefined, this can be fixed easily by changing request to xmlHttp or modifying xmlHttp = new XMLHttpRequest(); to be request = new .... same should be done to the other xmlHttp assignment.