当用户离开(关闭)页面时如何发送AJAX请求?

The Situation

Hi, I'm making a database-driven game, in which there is a question, and a user gains the right to change the question (i.e. write a new question) if they find the correct answer.

But this has an important issue, I think it's called a race condition. The issue is this:

  • User 1 finds the answer
  • User 1 is prompted to enter a new question
  • Before User 1 submits the new question, User 2 finds the new answer too
  • Now it's only luck, who is submitting the new question. If User 2 submits the question after User 1, User 2's question overwrites User 1's question.

Right now, I've fixed this issue by using some kind of semaphore, by keeping its timestamp. To summarize it works like this:

  • User 1 finds the answer
  • Semaphore is saved into database like ['user_ip' = 'x.x' , 'time'='y.y' , 'locked'='true']
  • Semaphore expires after t seconds
  • New question will be accepted only if semaphore is expired.

so when a new question is submitted, the application accepts it only if the semaphore is not locked, and the current time is larger by t (15) seconds than the semaphore's date.

But this has a problem too, User 2 is prompted

"You have found the answer, but somebody found it before you. You can change the question if they don't submit a new question in 15 seconds."

So the new winner has to wait 15 seconds, maybe unnecessarily.

Therefore,

What I Want to Do

I want to prompt the "winner" a form, with a stopwatch (time counter). When it reaches zero, it unlocks the semaphore so that the new winner can submit their question.

But this solution will have this problem:

If the winner closes the page before time counter reaches to zero, then the AJAX request will never be done and the semaphore will be locked indefinitely.

So I have to make sure I have called the userLeave(); function if the user closes the page.

Google suggests onbeforeunload and onunload but people also complain about those functions not working. So is there a 100%-sure way to send this AJAX call if a user (a winner) leaves the page ?

查看全部
du22399
du22399
2013/09/17 01:10
  • php
  • ajax
  • javascript
  • forms
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复