-2

在一页上,我向自己发送 AJAX 请求。使用 PHP 在成功函数中获得此请求后,我将新记录添加到某些 MySQL 数据库中的表“some_table”中。然后在同一个成功函数中,我从这个表中选择数据并通过 JQuery 在页面上显示它。问题是显示了所有旧记录,但没有显示我刚刚添加的记录:

$.ajax({
    url: 'http://somesite.com', 
    type: "POST",
    data: ({param1: value1, param2: value2, act: "I"}),
    success: function(data){
        <?php $mysqli = new mysqli("some_server", "some_database", "some_login", "some_password"); 
              $query = "INSERT INTO some_table VALUES ("'.$_POST["param1"].'","'.$_POST["param2"].'")";
              $mysqli->query($query);
              $mysqli->close();
        ?>
        alert("New record was added");
        <?php echo '$("#left_region").html(\'\');';
              $mysqli = new mysqli("some_server", "some_database", "some_login", "some_password"); 
              $result = $mysqli->query("SELECT some_column1, some_column2 FROM some_table"); 
              while($obj = $result->fetch_object()) { 
                  echo '$("#left_region").append("<p class=\"some_class\"><a href=\"#\">'.$obj->some_column1.'</a></p>");';
              } 
              $result->close();
              $mysqli->close();
        ?>
    }
});

有人可以提示如何解决吗?

4

1 回答 1

3

如果页面已经加载,您不能期望页面再次执行代码。

以此为例:

客户端:

$.post("some_url.php",{param1: value1, param2: value2, act: "I"},
      function(response){
         if(isNaN(response)==="true")
             $("#left_region").html(response);
         else
             alert("An error ocurred");
      }
)

服务器端:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("some_server", "some_database", "some_login", "some_password");
if ($_POST['act']) {
    $stmt = $mysqli->prepare("INSERT INTO some_table VALUES (?, ?)");
    $stmt->bind_param('ss', $_POST["param1"], $_POST["param2"]);
    $stmt->execute();

    $last_inserted_id = $mysqli->insert_id;
    $stmt = $mysqli->prepare("SELECT some_column1, some_column2 FROM some_table where some_column=?");
    $stmt->bind_param('s', $last_inserted_id);
    $stmt->execute();
    $result = $stmt->get_result();
    echo $result->fetch_assoc();
}

尝试这样的事情(如果有人发现错误,请更正,谢谢)。

于 2013-08-09T13:46:53.127 回答