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 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择