在javascript调用上从mysql数据库中选择 [英] SELECT from mysql database on javascript call

查看:120
本文介绍了在javascript调用上从mysql数据库中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用PHP和Javascript/jQuery构建的小型Web应用程序.

I have a small web app built in PHP and Javascript/jQuery.

该应用包含一个随机数生成器,当它落在数字4上时,用户即获胜.

The app involves a random number generator and when it lands on say number 4, the user wins.

但是,奖品是从数据库中提取的,每天赢得5个奖品.用户无法获胜.

However the prize is pulled from a database and after 5 prizes a day are won. the user is unable to win.

一旦用户获胜,奖品将更新为已排队",直到他们填写表格并领取奖品为止.然后从可用的奖品中取出.

Once a user wins, the prize is updated as 'queued' until they have filled out a form and claimed the prize. It is then taken out of available prizes.

如果用户刷新应用程序,则一切正常.但是,如果一个用户开始玩该应用程序,而另一个用户赢得了该应用程序,则该应用程序将不会更新,除非其更新是因为PHP是服务器端的.

This all works fine if the user refreshes the app. However if a user begins to play the app and another user wins then the app wont update unless its refreshed as PHP is server side.

我有一个JavaScript函数OnStart.因此,如果我可以在此处执行SQL查询,则每当用户丢骰子时都会发生.

I have a javascript function OnStart. So if i could perform the SQL query here it would happen everytime the user throws the die.

如何从jquery函数运行php语句?

How can I run a php statement from a jquery function?

如果有帮助,请执行以下语句:

If it helps here is the statement:

$result = mysql_query("SELECT * FROM prizes WHERE dateavailable='$todayDate' AND queue='0' AND won='0' ORDER BY id ASC LIMIT 1");

while($row = mysql_fetch_array($result))

{   
    $prize = $row['prize'];
}

谢谢

所以我可以在单独的文件中将类似的东西与php一起使用吗.

So could I possibly use something like this with the php in a seperate file.

<script type="text/javascript">
  function performAjaxSubmission() {
    $.ajax({
      url: 'file.php',
      method: 'POST',
      data: {
        action: 'save',
        arg1: 'val1',
        arg2: 'val2'
      },
      success: function() {
        alert("success!");
      }
    });
    return false; // <--- important, prevents the link's href (hash in this example) from executing.
  }

  jQuery(document).ready(function() {
    $("#linkToClick").click(performAjaxSubmission);
  });
</script>

推荐答案

将发布的代码保存在php文件中,我们将其称为 prizes_available.php .此文件还应该输出是否有奖品,因此创建结果对象并为其分配值:

Save the posted code in a php file, let's call it prizes_available.php. This file should also output whether prizes are available or not, so create the result object and assign the value to it:

$result = new stdclass();
$result->prizes_available = $prize != null;
echo json_encode($result);

如果您在浏览器中调用此脚本,它将输出如下内容:

If you call this script in browser, it will output something like this:

{ prizess_available: true }

使用jQuery,您可以轻松地将此字符串再次转换为对象:

Using jQuery, you can easily convert this string into an object again:

$.getJSON('prizes_available.php', function(result)  {
    if (!result.prizes_available) {
        alert('no more prizes');
    }
});

这篇关于在javascript调用上从mysql数据库中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆