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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器