duanbo2048 2013-08-28 13:09
浏览 39
已采纳

PHP轮询与同一页面上的结果

There was a great article posted by CSS-Tricks.com describing how to create a poll using PHP and a MySQL database. I've followed this and created a nice poll for myself. I noticed in the comments a mentioning of using AJAX to show the results on the same page instead of a completely separate page.

I am wondering what is the best way to display PHP Poll results on the same page?

UPDATE:

The answer is really simple. In fact, CSS-Tricks' poll without AJAX in my opinion is more difficult since it requires a database. This one does not!

The complete tutorial for creating a poll with PHP and AJAX is can be viewed here:

http://www.w3schools.com/php/php_ajax_poll.asp

I just wanted to clarify how to set the arrays up for more than two poll options. First you get the "database" (i.e. text file, not MySql).

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

Then you put the data in an array:

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

//if multiple options
$array = explode("||", $content[0]);
$option1array = $array[0];  //note: these values can be text values also.  If text value, nothing changes with this part of the code.  
$option2array = $array[1];
$option3array = $array[2];
$option4array = $array[3];

Store Data in "database"

if ($vote == 'option1')
  {
  $option1array = $option1array + 1;
  }
if ($vote == 'option2')
  {
  $option2array = $option2array + 1;
  }
if ($vote == 'option3')
  {
  $option3array = $option3array + 1;
  }
if ($vote == 'option4')
  {
  $option4array = $option4array + 1;
  }

Then, output your results. For file structure and AJAX script, see the complete tutorial.

  • 写回答

1条回答 默认 最新

  • duanchun6148 2013-08-28 13:16
    关注

    You have two options:

    1) Use ajax just as you suggested in your question, when you submit the vote via ajax, get the results back as the response.

    2) Get the results before the vote is submitted, it will still need to be submitted via ajax if you want to stay on the same page. But instead of using ajax to get back the results, since you have the results prior to the vote you could just add one vote to the appropriate selection choice, then use Javascript / CSS to change the results from hidden to displayed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要