我注意到当我在 .each() 循环内的 jQuery 中使用 AJAX 时遇到问题。脚本执行时,仅更新我数据库中的第一条记录。
这是我的脚本:
function save(){
var _userTypeId;
var _userTypeName;
var _isDeleted;
var request;
$("tr.recUserType").each(function(){
$this = $(this);
_userTypeId = $this.find("#userTypeId").html();
_userTypeName = $this.find("#userTypeName").val();
_isDeleted = $this.find("#isDeleted").val();
request = $.ajax({
url: "save.php",
type: "POST",
data: {userTypeId: _userTypeId, userTypeName: _userTypeName, isDeleted: _isDeleted}
});
});
request.done(function(){
document.location.reload();
});
request.fail(function(){
alert("Request Failed!");
});
}
以及 save.php 的内容:
<?php
include_once "globals.php";
dbConnect();
$isExisting = mysql_query("SELECT COUNT(userTypeId) AS userCount FROM userType WHERE userTypeId='".$_POST['userTypeId']."';");
$result = mysql_fetch_array($isExisting);
//original: if(!$result['userCount'] = 0) <-- This was a logical error
if($result['userCount'] != 0)
mysql_query("UPDATE userType SET userTypeName='".$_POST['userTypeName']."', isDeleted='".$_POST['isDeleted']."' WHERE userTypeId='".$_POST['userTypeId']."';");
else
mysql_query("INSERT INTO userType VALUES('', '".$_POST['userTypeName']."', '".$_POST['isDeleted']."');");
echo mysql_error();
dbClose();
?>
我读过我可以选择使用同步而不是异步,但我也读过这不是一个好习惯。
那么我如何真正做到异步完成并解决问题呢?