尝试使用jquery,ajax和php提交表单

时间:2014-03-01 17:44:41

标签: javascript php jquery ajax

我知道有很多这样的问题,但没有一个对我有用。

我有一个表单,需要在没有页面重新加载的情况下提交,而这种情况发生时我需要生成一个随机数。

这是我的代码: http://pastebin.com/9M4g2qNL

<!DOCTYPE HTML>
<html>
<head>
        <meta http-equiv="content-type" content="text/html" />
        <meta name="author" content="Tom Heek" />
    <script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
    <script src="js/jquery-1.10.2.min.js"></script>

        <title>Index</title>  
</head>

<body>

<?php

/**
* @author Tom Heek
* @copyright 2014
*/

   $max = '1000';
   $rand = rand(1,$max);
   echo $rand;

?>

<form action="" id="guess" method="POST">
<input type="number" value="1" min="1" max="10" />
<input type="submit" value="Bet" />
<p style="display: none;">Please enter a number between 1 and <?php echo $max; ?></p>
</form>

<script type="text/javascript" charset="utf-8">
var t = false

$('input').focus(function () {
    var $this = $(this)

    t = setInterval(

    function () {
        if (($this.val() < 1 || $this.val() > 1000) && $this.val().length != 0) {
           if ($this.val() < 1) {
               $this.val(1)
           }

           if ($this.val() > 1000) {
               $this.val(1000)
           }
           $('p').fadeIn(1000, function () {
               $(this).fadeOut(1000)
           })
       }
   }, 50)
})

$('input').blur(function () {
   if (t != false) {
       window.clearInterval(t)
       t = false;
    }
})
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可能希望使用ajax发布表单数据。这可以通过向按钮的click事件添加类似的内容来完成

$('#BetButton').click(function () {
    var value = $('#BetInput').val();
    $.post("page.php", { bet: value }, function(result) {
      // handle result
    });
});

此示例要求您在输入中添加相应的ID(BetButtonBetInput)。要使表单不发布,您需要从表单标记中删除action=""method="POST"