我尝试使用纯 javascript Ajax将当前页面 URL ( window.location.href)传递给php 变量。我究竟做错了什么? $_REQUEST['url']
计数器.js:
'use strict';
let clicks = document.querySelectorAll('.Counter-trigger'); // IE8
let voted = localStorage.getItem('voted');
let message = document.getElementById('Counter-message');
let count = document.getElementById('Counter-count');
let i;
let url;
let post;
let xhr;
for (let i = 0; i < clicks.length; i++) {
clicks[i].onclick = function () {
if (voted == 'voted') {
message.innerHTML = "Sorry, ...!!";
} else {
let url = window.location.href;
let post = url; // post string
let xhr = new XMLHttpRequest();
xhr.open('POST', './lib/Counter/CounterReq.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200) return;
console.log(xhr.responseText);
message.innerHTML = "Thanks!!";
count.innerHTML = +count.textContent+1;
};
xhr.send(post);
localStorage.setItem('rate', 'voted');
voted = 'voted';
}
}
}
CounterReq.php
$url = $_REQUEST['url']; // posted from page
$origin = $_SERVER['DOCUMENT_ROOT'].parse_url($url,PHP_URL_PATH);
$file = '_Counter.txt'; // counts is saved in this document
$file_path = $origin.'_Counter.txt'; // counts is saved here
$count = file_get_contents($file_path);
if ($count == null){$count = 0; echo $count;
}
$count++; // increment count by 1
$handle = fopen($file_path, "w+");
flock($handle,LOCK_EX); // LOCK_EX (2) exclusive locking for write access
fwrite($handle, $count);
flock($handle,LOCK_UN); // LOCK_EX (3) Releases a lock
fclose($handle); // close file
泛舟湖上清波郎朗
哔哔one
呼唤远方
随时随地看视频慕课网APP