AJAX POST数据不起作用

时间:2014-03-27 13:56:21

标签: php jquery ajax

这是我的jQuery-Ajax代码:

<script>
    $('#sbmt').click( function(){
        $.ajax({
        type: 'post',
        data: $("#ajxfrm").serialize(),
        url: "postdata.php",
        cache: false,
        success: function (data)
        {
          alert('updated table');
        }
        });
    });
</script>

HTML CODE:

<form id="ajxfrm" method="post" action=""> 

<label>HIGH :  </label>  <input type="text" name="hi"  id="hi"><br><br>

<label>LOW :  </label><input type="text" name="lo"  id="lo"><br><br>

<label>OPENING STOCK :  </label><input type="text" name="opn" id="opn"><br><br>

<label>CLOSING STOCK :  </label><input type="text" name="cls" id="cls">

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

</form>

和postdata.php文件上的PHP代码是:

require_once 'config.php';

$hi  = $_POST['hi'];

$lo = $_POST['lo'];

$opn = $_POST['opn'];

$cls = $_POST['cls'];

echo $hi;

$postdata = "INSERT INTO htmdem ( high,low,open,close ) VALUES('$hi','$lo','$opn','$cls');";

mysql_query($postdata);

当通过没有ajax的表单发布时,表格会更新,但是使用AJAX时却没有。请在这里说明错误。非常感谢

4 个答案:

答案 0 :(得分:2)

修改你的html以添加形式的动作:

<form id="ajxfrm" method="post" action="postdata.php"> 

尝试处理表单提交事件:

$('#ajxfrm').submit(function(event){
        $.ajax({
        type: 'post',
        data: $(this).serialize(),
        url: $(this).attr("action"),
        cache: false,
        success: function (data)
        {
          alert('updated table');
        }
        });
       return false; //to prevent form submission
      //or event.preventDefault();
    });

BTW,不推荐使用成功回调,并且不会缓存帖子请求,因此我们也不需要cache:false

$('#ajxfrm').submit(function(event){
      $.ajax({
            type: 'post',
            data: $(this).serialize(),
            url: $(this).attr("action")
            })
            .done(function (data){
               alert('updated table');
            });
           return false; //to prevent form submission
           //or event.preventDefault();
     });

答案 1 :(得分:2)

更改输入类型=&#34;提交&#34;输入type =&#34; button&#34;。这应该是我猜的技巧。

答案 2 :(得分:2)

试试这个:别忘了将表单操作设置为 postdata.php

jQuery(function($) {
    $('#ajxfrm').submit( function(e){
        $.ajax({
            type: 'post',
            data: $(this).serialize(),
            url: $(this).attr("action")
        })
                .done(function (data){
                    alert('updated table');
                });
        e.preventDefault();
    });
});

答案 3 :(得分:1)

假设您已在页面中包含jquery库,

首先,使用firefox / chrome运行您的页面并使用他们的firebug / console来验证您的ajax实际上是否将数据发布到您的php页面。

其次,在php文件中修改查询执行,以捕获查询错误:

mysql_query($postdata) or die(mysql_error());

其中一个案例将帮助您确定问题

对于Firefox:从https://getfirebug.com/获取Firebug插件 安装并重新启动Firefox后,按F12。控制台将打开。
运行您的ajax调用并检查控制台是否有数据发布。

相关问题