ajax each 加if,jQuery AJAX solution inside each() loop

在使用jQuery的AJAX和each()循环更新数据库记录时,遇到问题:只有第一条记录被更新。AJAX请求在成功后刷新页面,但未处理所有记录。已知可以设置同步执行,但考虑到这不是最佳实践,寻求异步解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have noticed that I'm having problems when I'm using AJAX in jQuery inside a .each() loop. Only the first record in my database are being updated when the script executes.

Here's my script:

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!");

});

}

And the contents of save.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)

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();

?>

I have read that I have the option to use synchronous instead of asynchronous, but I have also read it is not a good practice.

So how do I actually get this done asynchronously and fix the problem?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值