延迟动态更新以从数据库获取正确的值
我有这个 jQuery 代码,可以对照片进行评级,然后更新数据库中的评级。函数 updateRating
应该用新的评级更新显示,但有时却不会。我该如何确保显示正确的评级?
$("#rate").click(
function(){
ratePhotoById( $("#image").attr( 'id' ) );
updateRating( $("#image").attr( 'id' ) );
return false;
}
);
function ratePhotoById( imageId ){
$.post(
"ImageRate.php",
{ ... },
function(data) {
// process
// console.log(data);
}
);
}
PS:理想情况下,这应该通过某种回调模式来完成。这可能吗?
I have this jQuery code that rates a photo and then updates it's rating in the database. The function updateRating
should update the display with the new rating but sometimes it doesn't. What can I do to ensure that the correct rating is displayed?
$("#rate").click(
function(){
ratePhotoById( $("#image").attr( 'id' ) );
updateRating( $("#image").attr( 'id' ) );
return false;
}
);
function ratePhotoById( imageId ){
$.post(
"ImageRate.php",
{ ... },
function(data) {
// process
// console.log(data);
}
);
}
P.S: Ideally this should be done doing some sort of callback pattern. Would this be possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:基于问题的更新...
将ratePhotoById更改为:
并从点击事件处理程序中删除对updateRating的调用
OLD:
我猜你正在使用ajax来更新评级(通过ratePhotoById函数)。
将调用移至 updateRating 函数,作为ratePhotoById ajax 调用中成功回调的一部分
像这样的东西:
EDIT: Based on the update to the question...
Change the ratePhotoById to:
and remove the call to updateRating from the click event handler
OLD:
I guess you are using ajax to update the rating (via ratePhotoById function).
Move the call to updateRating function as a part of the Success callback in the ratePhotoById ajax call
Something like:
您还可以返回 $.ajax 返回的延迟,这可以让您稍微解耦事物。
然后你可以使用deferred的done(cb)方法。这将使用 AJAX 请求的结果调用回调函数,无论它已经返回还是仍将返回。
Deferred 对象还有一些其他不错的方法,例如fail() 和pipe()。查看 Deferred 的文档以获取更多信息: http://api.jquery.com/category/延迟对象/
You can also return the deferred that $.ajax returns, which lets you decouple things a bit.
Then you can use the deferred's done(cb) method. This will call the callback function with the result of the AJAX request, whether it has already returned or is going to return still.
The Deferred object also has some other nice methods, like fail() and pipe(). Check out the documentation for Deferred for more info: http://api.jquery.com/category/deferred-object/