如何使用 AJAX 提交表单并返回输入值的摘要


How to submit a form with AJAX and return a summary of the input values

我有一个多部分表单,正在使用jQuery表单插件。

当用户完成表单的一部分并单击"继续"时,我想将该信息发送到服务器,然后在同一页面上提供所提交信息的摘要。使用我当前的代码,除非在提交之前完成所有字段,否则我会收到错误。我的猜测是我的PHP是完全错误的,我在"data:"之后输入的信息也是不正确的。

关于如何使其正常工作的任何建议?

.PHP:

$return['message'] = array(); 
if ($_POST['markName1']) {
$return['message'][]='Text' . $_POST['markName1'];
}
if ($_POST['markDescription1']) {
$return['message'][]='More text' . $_POST['markDescription1'];
}
 if ($_POST['YesNo1']) {
$return['message'][]='' . $_POST['YesNo1'];
}
echo json_encode($return);

j查询:

$(form).ajaxSubmit({                
   type: "POST",
   data: {
          "markName1" : $('#markName1').val(),
          "markDescription1" : $('#markDescription1').val()
                       },
   dataType: 'json',
   url: './includes/ajaxtest3.php',
 //...
   error: function() {alert("error!");},                    
   success: $('#output2').html(data.message.join('<br />'))
//...

.HTML:

<form id="mark-form">
 <div class="markSelection">
    <input type="checkbox" >
      <label for="standardCharacter"></label>
              <span class="markName-field field">
                <label for="markName1" ></label>
                <input type="text" name="markName1" id="markName1">
              </span>   
         <label for="markDescription1"></label>
         <textarea id="markDescription1" name="markDescription1"></textarea>
       <ul class="YesNo">
         <li>
           <input type="radio" name="YesNo1" value="Yes">
             <label for="Yes">Yes</label>
         </li>
         <li>
           <input type="radio" name="YesNo1" value="No">
           <label for="No">No</label>
         </li>
       </ul>
  </div>
  <div class="step-section">
    <p>
    <span class="next-step">
      <button id="submit-second" class="submit" type="submit" name="next">Next</button>
    </span>
   </p>
 </div>
</form> 

不需要用引号括起来markName1:$('#markName1').val()markDescription1 : $('#markDescription1').val()

尝试将其用于您的成功回调

success: function(html) {
        alert(html);
    }

你应该把你的PHP改成这样:

$markName1 = $_POST['markName1'];
$markDescription1 = $_POST['markDescription1'];
$YesNo1 = $_POST['YesNo1'];
if(!empty($markName1)){
echo 'Text' . $markName1;
}
if(!empty($markDescription1)){
echo 'More Text' . $markDescription1;
}
if(!empty($YesNo1)){
echo $YesNo1;
}

注意我将成功函数数据类型更改为 html

编辑 2

<form>外部创建一个按钮,并将您的 AJAX 替换为以下内容:

$('#submit-button').click(function() {
    $.post('./includes/ajaxtest3.php', $('#mark-form').serialize(), function(html) {
        document.getElementById('someDiv').write(html);
    }
    });