首页 文章

jquery Ajax POST发布但未收到?

提问于
浏览
0

我完全糊涂了:

这是我的php脚本“add_credits.php” . 如果我创建一个表单并通过method =“post”调用它,它运行得很好 .

$stmt = "UPDATE sites SET credits=:credits WHERE id=:id";
$stmt = $db->prepare($stmt);
$stmt ->execute( array( ":credits" => $_POST['cred'], ":id" => $_POST['id'] ) );

这是我的输入字段,触发jquery / ajax .

<input id="<?php echo $row['id']; ?>" type="text" class="credits" value="<?php echo $row['credits']; ?>" />

这是我的jquery,它会在成功时正确回显警报框中的变量 .

$(".credits").bind('input', function() {
            var add_id = $(this).attr("id");
            var info = 'id=' + add_id;                
            var add_cred = $(this).attr("value");
            var info2 = 'cred=' + add_cred;
                $.ajax({
                    type : "POST",
                    url : "add_credits.php", //add credits on enter php script
                    data : {info:info, info2:info2},
                    success : function() {
                       alert(info2);
                    }
                });
            return true;
});

那么为什么它的报告成功,但没有执行UPDATE,好像php没有收到$ _POST细节?我错过了什么?

2 回答

  • 0

    您不必手动序列化这样的数据

    $('.credits').on('input', function() {
      var req = $.post('add_credits.php', {
        info: $(this).attr('id'),
        info2: $(this).attr('value')
      });
      req.done(function(res) {
        console.log(res);
      });
      req.fail(function(err) {
        console.error(err);
      });
    });
    

    在PHP方面,请确保您正在阅读 infoinfo2

    // info and info2 were set in the POST request in the jQuery above
    $info = $_POST['info'];
    $info2 = $_POST['info2'];
    
    do_something($info, $info2);
    
    // respond in some way
    header('content-type: application/json');
    echo json_encode(['ok'=> true]);
    

    您可以将字段命名为 idcred ,如果这是您所希望的 . 这会将jQuery数据更改为此

    var req = $.post('url', {
      id: $(this).attr('id'),
      cred: $(this).attr('value')
    });
    

    然后确保在PHP中阅读 $_POST['id']$_POST['cred']

  • 0

    使用以下jquery代码:

    $(".credits").bind('input', function() {
                var add_id = $(this).attr("id");
                var info = add_id;                
                var add_cred = $(this).attr("value");
                var info2 = add_cred;
                    $.ajax({
                        type : "POST",
                        url : "add_credits.php", //add credits on enter php script
                        data : {id:info, cred:info2},
                        success : function() {
                           alert(info2);
                        }
                    });
                return true;
    });
    

相关问题