【发布时间】:2017-01-12 15:50:00
【问题描述】:
我在做什么?
我正在尝试通过调用 PHP 脚本,使用 jQuery 的 ajax 函数在 MySql 数据库中插入数据。
有什么问题?
数据被插入数据库两次。
HTML 代码:
<button id="insert">Insert</button>
<script>
$('#insert').click(function(){
$.ajax({
type: "GET",
url: 'url-of-php-script-here',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
alert(data.status);
}
});
});
</script>
PHP 脚本:
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$custId = $_GET["custId"];
$tableId = $_GET["tableId"];
try {
$statement = $conn->prepare("INSERT INTO reservation_master(cust_id,table_id) VALUES(:custId, :tableId)");
$statement->execute(array(
"custId" => $custId,
"tableId" => $tableId
));
$reservId = $conn->lastInsertId();
$result = array("status"=>"reserved", "cust_id"=> $custId , "table_id"=> $tableId, "reserv_id"=> $reservId);
echo json_encode($result);
}
catch(PDOException $e)
{
$result = array("status"=>"failed");
echo json_encode($result);
}
更新 1
我尝试使用表单调用脚本并且它工作正常。我认为问题在于ajax。我使用了以下代码:
<form method="get" action="url-of-php-script-here">
<input name="custId" type="text"></input>
<input name="tableId" type="text" ></input>
<input type="submit"></input>
</form>
【问题讨论】: