2014-04-26 66 views
1

我在我的網站上有一個表單。問題存儲在數據庫中,一些變量決定你看到的問題。因此,問題的數量是未知的。對於這些問題的代碼是這樣的:未知數量變量的AJAX帖子

HTML

<ol class="questions"> 
    <?php 
    $number = 1; 
     while($row = mysql_fetch_assoc($result)) { 
      echo '<li>'; 
       echo '<span><label for="q'.$number.'">'.$row['question'].'</label></span>'; 
       echo '<input id="q'.$number.'" name="q'.$number.'" type="text" value="'.$row['description'].'" onclick="this.value="";this.onclick="test";this.style.color="#000000"; setAttribute("type", "text");" onfocus="if (this.value == "'.$row['description'].'") {this.value = ""; setAttribute("type", "text");}" onblur="if (this.value == "") {this.value = "'.$row['description'].'";setAttribute("type", "text");}"/>'; 
      echo '</li>'; 
      $number++; 
    };?> 
</ol> 

現在,在提交我要發佈這些問題的答案與AJAX的形式。我該如何處理未知數量的問題?

+0

哪裏是ajax代碼? – Geo

回答

1

正如前面作者所說的使用serialize()函數。他沒有提到我現在要澄清的事情。

JavaScript代碼:

$("#button").on("click", function() { 
    $.ajax({ 
     url: "someurl.php", 
     method: "post", 
     data: $("#myform").serialize() 
    }); 
}); 

和HTML代碼必須是這樣:

<form id="myForm"> 
    <input type='text' name='field1' /> 
    <input type='text' name='field2' /> 
    <input type='text' name='etc' /> 
</form> 
<a href='#' id="button">Send ajax</a> 

現在,當你點擊Send ajax按鈕,表格將被序列化(這意味着創建的字符串,這將包含有效的url查詢,所以它可以隨請求發送)。閱讀關於這裏:https://api.jquery.com/serialize/

希望,這將有所幫助。

問我是否有什麼不清楚。

+0

謝謝!它的工作,第二個問題是;我如何在PHP中捕獲它? – user2755352

+0

@ user2755352您是否創建了新的問題或者什麼?或者你現在問我? –

+0

我現在問你是否也知道第二個問題的答案; p – user2755352

1

你可以通過像這樣的ajax提交你的表單。

$("#myForm").submit(function() { 
    $.post('post.php',$(this).serialize(), function(data) { 
     alert(data); 
    }); 

    return false; 
});