0

一个表单加载到我的 ajax div 中,但是一旦用户提交表单数据,整个屏幕都会重新加载表单结果,而理想情况下它应该只是加载到同一个 ajax div 中。

我当前的工作 ajax 代码如下所示:

<!-- starts ajax code -->    
<script>
    window.onload = function () {
        var everyone = document.getElementById('everyone'),
            searching = document.getElementById('searching');

        everyone.onclick = function() {
            loadXMLDoc('indexEveryone');
            everyone.className = 'filterOptionActive';
            searching.className = 'filterOption';
        }

        searching.onclick = function() {
            loadXMLDoc('indexSearching');        
            searching.className = 'filterOptionActive';
            everyone.className = 'filterOption';
        }

        function loadXMLDoc(pageName)
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
                }
              }

            function get_query(){
              var url = location.href;
              var qs = url.substring(url.indexOf('?') + 1).split('&');
              for(var i = 0, result = {}; i < qs.length; i++){
                qs[i] = qs[i].split('=');
                result[qs[i][0]] = decodeURIComponent(qs[i][1]);
              }
              return result;
            }

            xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
            xmlhttp.send();
            }
    }
    </script>
    <!-- ends ajax script -->

如何使用此代码确保此表单加载到 ajax 窗口中?

<form name="searchLocations" action="/indexSearchingSubmit.php" method="POST">
        <select name="locationName">
            <?php 
            $sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
            while ($row = mysql_fetch_array($sql)){
            echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
            }
            ?>
        </select>
        <input type="submit" value="Submit">
    </form>
4

1 回答 1

0

例如,在您的表单中,您不应该通过替换来提交它:

<input type="submit" value="Submit">

=> 并使用 JavaScript 函数在本地执行此操作:

<input type="button" value="Load" onclick="loadXMLDoc('/indexSearchingSubmit.php'); return false;">

当 AJAX 返回时,它使用 as 指定您的 js 代码:

document.getElementById("leftCont").innerHTML=xmlhttp.responseText;

将响应写入 div leftCont。无需更改您当前的整个页面。

如果要传参数给ajax调用,il会比较复杂。

这是一个 IE 检查示例,使用formserialize()获取表单数据:

<html>
<!-- starts ajax code -->  
<head>
<script>
function formserialize (form) {
  if (!form || form.nodeName !== "FORM") {
    return;
  }
  var i, j, q = [];
  for (i = form.elements.length - 1; i >= 0; i = i - 1) {
    if (form.elements[i].name === "") {
      continue;
    }
    switch (form.elements[i].nodeName) {
      case 'INPUT':
        switch (form.elements[i].type) {
          case 'text':
          case 'hidden':
          case 'password':
          case 'button':
          case 'reset':
          case 'submit':
            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
            break;
          case 'checkbox':
          case 'radio':
            if (form.elements[i].checked) {
              q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
            }                                               
            break;
        }
        break;
      case 'file':
        break; 
      case 'TEXTAREA':
        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
        break;
       case 'SELECT':
         switch (form.elements[i].type) {
           case 'select-one':
             q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
             break;
           case 'select-multiple':
             for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
               if (form.elements[i].options[j].selected) {
                 q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
               }
             }
             break;
           }
           break;
         case 'BUTTON':
           switch (form.elements[i].type) {
             case 'reset':
             case 'submit':
             case 'button':
               q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
               break;
           }
           break;
         }
  }
  return q.join("&");
}

function loadXMLDoc(pageName)
{
  var xmlhttp, formdata;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("leftCont").innerHTML = xmlhttp.responseText;
    }
  }
  var url;
  if(pageName)
  {
    url = "../browse/" + pageName + ".php?user=" + get_query()['user'];
  }
  else
  {
    url = window.location.href;
  }
  formdata = formserialize(document.forms["searchLocations"]);
  xmlhttp.open("GET", url, true);
  xmlhttp.send(formdata);
}

function get_query(){
  var url = location.href;
  var qs = url.substring(url.indexOf('?') + 1).split('&');
  for(var i = 0, result = {}; i < qs.length; i++){
    qs[i] = qs[i].split('=');
    result[qs[i][0]] = decodeURIComponent(qs[i][1]);
  }
  return result;
}

window.onload = function () {
  var everyone = document.getElementById('everyone'),
     searching = document.getElementById('searching');

  everyone.onclick = function() {
    loadXMLDoc('indexEveryone');
    everyone.className = 'filterOptionActive';
    searching.className = 'filterOption';
  }

  searching.onclick = function() {
    loadXMLDoc('indexSearching');  
    searching.className = 'filterOptionActive';
    everyone.className = 'filterOption';
  }
}
</script>
<!-- ends ajax script -->
</head>
<body>
<form name="searchLocations" action="/indexSearchingSubmit.php" method="POST">
<select name="locationName">
<?php 
  //
  // define MySQL query params before to do this:
  //...
  $sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
  while ($row = mysql_fetch_array($sql)){
    echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
  }
?>
</select>
<input type="button" value="Load" onclick="loadXMLDoc(); return false;" />
<input type="text" name="myname" value="Elaine" />
</form>

<div id="everyone"></div>
<div id="searching"></div>
<div id="leftCont" style="background-color: gold; width: 600px; height: 200px;"></div>
</body>
</html>
于 2013-10-27T18:43:59.210 回答