@W1SE2018
Вёрстка, дизайн, инвестиции, бизнес

Ajax для готовой системы рейтинга (статичный сайт), как реализовать?

Здравствуйте, уважаемые знатоки!

Суть:

Есть готовый скрипт рейтинга, работающий на PHP+MYSQL+JS, работает как надо, без перезагрузки страницы. НО, когда я добавляю header LastModified (средствами PHP) и получаю ответ сервера 304, данные с бд не подгружаются и остаются неизменными, потому что при повторном обновлении страницы, браузер берёт уже закешированную копию, так как код ответа - 304, следовательно нужно реализовать AJAX. Перелопатил инет, были примеры, пробовал несколько часов - ничего не получается. Прошу, кто разбирается, подскажите пожалуйста как подправить это, спасибо!!!

Файлы рейтинг системы:

- 1) c-rating.php
<?php
//Connect to  your rating database
	$rating_dbhost        = 'localhost';
	$rating_dbuser        = 'pass';
	$rating_dbpass        = 'pass';
	$rating_path_db       = ''; // the path to your db.php file (not used yet!)
	$rating_path_rpc      = ''; // the path to your rpc.php file (not used yet!)
	
	$rating_unitwidth     = 36; // the width (in pixels) of each rating unit (star, etc.)
	// if you changed your graphic to be 50 pixels wide, you should change the value above
	
$rating_conn = mysqli_connect($rating_dbhost, $rating_dbuser, $rating_dbpass) or die  ('Error connecting to mysql');
	//mysql_select_db($rating_dbname);

?>


- 2) _drating.php
<?php

function rating_bar($id,$units='',$static='') { 

require('rating.php'); // get the db connection info
	
//set some variables
$ip = $_SERVER['REMOTE_ADDR'];
if (!$units) {$units = 10;}
if (!$static) {$static = FALSE;}


// insert the id in the DB if it doesn't exist already

$numbers=mysqli_fetch_assoc($query);


if ($numbers['total_votes'] < 1) {
	$count = 0;
} else {
	$count=$numbers['total_votes']; //how many votes total
}
$current_rating=$numbers['total_value']; 
// now draw the rating bar
$rating_width = @number_format($current_rating/$count,2)*$rating_unitwidth;
$rating1 = @number_format($current_rating/$count,1);
$rating2 = @number_format($current_rating/$count,2);


if ($static == 'static') {

		$static_rater = array();
		$static_rater[] .= "\n".'<div class="ratingblock">';
		$static_rater[] .= '<div id="unit_long'.$id.'">';
		$static_rater[] .= '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
		$static_rater[] .= '<li class="current-rating" style="width:'.$rating_width.'px;">Currently '.$rating2.'/'.$units.'</li>';
		$static_rater[] .= '</ul>';
		$static_rater[] .= '</div>';
		$static_rater[] .= '</div>'."\n\n";

		return join("\n", $static_rater);


} else {

      $rater ='';
      $rater.='<div class="ratingblock">';

      $rater.='<div id="unit_long'.$id.'">';
      $rater.='  <ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
      $rater.='     <li class="current-rating" style="width:'.$rating_width.'px;">Currently '.$rating2.'/'.$units.'</li>';

      for ($ncount = 1; $ncount <= $units; $ncount++) { // loop from 1 to the number of units
           if(!$voted) { // if the user hasn't yet voted, draw the voting stars
              $rater.='<li><a href="db.php?j='.$ncount.'&amp;q='.$id.'&amp;t='.$ip.'&amp;c='.$units.'" title="'.$ncount.' out of '.$units.'" class="r'.$ncount.'-unit rater" rel="nofollow">'.$ncount.'</a></li>';
           }
}

$ncount=0;

$rater.='</ul>';

$rater.='<p class="voted"';

if($voted){ $rater.=''; }

$rater.='>Рейтинг: <strong>'.$rating1.'</strong>/<strong>'.$units.'</strong> &nbsp; &nbsp; '.$tense.': <strong>'.$count.'</strong>';

$rater.=' </p>';


$rater.='<meta itemprop="bestRating" content="'.$units.'">';

$rater.='<meta itemprop="worstRating" content="1">';

$rater.='<meta itemprop="ratingValue" content="'.$rating1.'">';

$rater.='<meta itemprop="ratingCount" content="'.$count.'">';

$rater.='</div>';

$rater.='</div>';

return $rater;

}

}

?>

- 3) db.php

- 4) rpc.php

- 5) rating.js
var xmlhttp
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	  try {
	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	 } catch (e) {
	  try {
	    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	  } catch (E) {
	   xmlhttp=false
	  }
	 }
	@else
	 xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	 try {
	  xmlhttp = new XMLHttpRequest();
	 } catch (e) {
	  xmlhttp=false
	 }
	}
	function myXMLHttpRequest() {
	  var xmlhttplocal;
	  try {
	    xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
	 } catch (e) {
	  try {
	    xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
	  } catch (E) {
	    xmlhttplocal=false;
	  }
	 }

	if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
	 try {
	  var xmlhttplocal = new XMLHttpRequest();
	 } catch (e) {
	  var xmlhttplocal=false;
	  alert('couldn\'t create xmlhttp object');
	 }
	}
	return(xmlhttplocal);
}

function sndReq(vote,id_num,ip_num,units) {
	var theUL = document.getElementById('unit_ul'+id_num); // the UL
	
	// switch UL with a loading div
	theUL.innerHTML = '<div class="loading"></div>';
	
    xmlhttp.open('get', 'rpc.php?j='+vote+'&q='+id_num+'&t='+ip_num+'&c='+units);
    xmlhttp.onreadystatechange = handleResponse;
    xmlhttp.send(null);	
}

function handleResponse() {
  if(xmlhttp.readyState == 4){
		if (xmlhttp.status == 200){
       	
        var response = xmlhttp.responseText;
        var update = new Array();

        if(response.indexOf('|') != -1) {
            update = response.split('|');
            changeText(update[0], update[1]);
        }
		}
    }
}

function changeText( div2show, text ) {
    // Detect Browser
    var IE = (document.all) ? 1 : 0;
    var DOM = 0; 
    if (parseInt(navigator.appVersion) >=5) {DOM=1};

    // Grab the content from the requested "div" and show it in the "container"
    if (DOM) {
        var viewer = document.getElementById(div2show);
        viewer.innerHTML = text;
    }  else if(IE) {
        document.all[div2show].innerHTML = text;
    }
}

/* =============================================================== */
var ratingAction = {
		'a.rater' : function(element){
			element.onclick = function(){

			var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
			var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
			var parameterList = new Array();

			for (j = 0; j < parameterTokens.length; j++) {
				var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
  • Вопрос задан
  • 150 просмотров
Решения вопроса 1
inoise
@inoise Куратор тега PHP
Solution Architect, AWS Certified, Serverless
Удивлен что ещё не ответили вам. Наверняка эту простыню никто не будет читать. Тем более что вы не оформили ее как код

Не ставьте этот заголовок. Это дефолтное поведение браузера. По сути, у вас есть API, а оно не должно отвечать за это. Если хотите кэшировать на определенный срок то храните данные в localStorage
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы