我的ajax电话后,该帖子怎么会变得空白



我有一个ajax调用:

function change(x){
    var id=x;
    alert(id);
    $.ajax({
        url: "http://localhost/kidsKnitsDB/edit.php",
        type: "post",
        data: JSON.stringify(id),
        beforeSend: function(response){alert('Sending');},
            success: function(response){ alert('success');},
            error: function(response){alert('failed');},
            complete: function(response){window.location="http://localhost/kidsKnitsDB/edit.php";},
    });
}

从中获取数据:

<?php for($r=0; $r<count($result); $r++){?>
    <tr>
        <?php for($c=0; $c<9; $c++){?>
            <td><?php echo $result[$r][$c];?></td>
        <?php }?>
        <td><button name="edit<?php echo $r;?>" onclick="change(<?php echo $result[$r][0];?>)">edit</button></td>
    </tr>
<?php }?>

,它应该发布到:

<?php 
    $db= new PDO("mysql:host=example;dbname=example", "root", "example");
    $id=$_POST['id'];
    $query= $db->prepare("SELECT * FROM table WHERE Id = :parameter");
    $query->bindParam(':parameter', $id, PDO::PARAM_STR);
    $query->execute();
    $result=$query->fetch();
    $name=$result['Name'];
?>
<script type="text/javascript">alert(<?php echo $id;?>);</script>
<h1>Edit for <?php echo $name;?></h1>
</br>
<form id="editForm" action="sucess.php" method="POST">
    <lable>sale price</lable>
    <input type="number" id="salePrice" name="salePrice">
    </br>
    <lable>cost</lable>
    <input type="number" id="cost" name="cost">
    </br>
    <lable>contents</lable>
    <input type="text" id="contents" name="contents">
    </br>
    <lable>on sale</lable>
    <input type="checkbox" id="onSale" name="onSale">
    </br>
    <lable>image</lable>
    <input type="image" id="image" name="image">
    </br>
    <lable>active</lable>
    <input type="checkbox" id="active" name="active">
    </br>
</form>

但是,$ id是空白的,我相信这是因为Ajax呼叫以某种方式,但我不确定。如果有人可以提供帮助,那就太好了。

第一个问题

您只是发送一个数字,而不是一个对象,因此PHP代码不知道您将其称为ID。

更改

function change(x){
  var id=x;

to

function change(x){
  var id={id:x};

第二个问题

使用此代码:

complete: function(response){window.location="http://localhost/kidsKnitsDB/edit.php";}

完成Ajax-call完成后进行重定向。

这就是发生的事情:

  1. 第一个Ajax-Request发送到服务器。由于您解决了第一个问题,因此现在将数字在命名的后变量中获取。
  2. 服务器生成页面并作为对您的ajax-call的答复。
  3. 当Ajax-call完成后,您将手动重定向到您刚刚发送Ajax-Request的同一页面,但是您在不提供任何变量的情况下进行。
  4. 浏览器加载页面,但是由于请求中没有ID,因此ID为空白。

从您的日志文件中,您可以看到它提出了两个请求,第一个请求和ID,第二个没有任何变量:

[Sun Jan 26 19:08:29 2014] Arrayn(n [id] => 2n)n
[Sun Jan 26 19:08:30 2014] Arrayn(n)n

我认为Ajax呼叫使它比在这种情况下需要的更为复杂。将链接链接到http://localhost/kidsKnitsDB/edit.php?id=x中更简单,其中X是数字。然后,您还应该将$ _post更改为php代码中的$ _get。

如果您仍然想使用Ajax,则应插入页面上某个地方的请求中获得的响应,而不是像现在这样做的重定向。

最新更新