【问题标题】:count button pass the current page URL with pure javascript Ajax to the php variable计数按钮将带有纯 javascript Ajax 的当前页面 URL 传递给 php 变量
【发布时间】:2019-12-25 19:30:50
【问题描述】:

我尝试使用 纯 javascript Ajax 将当前页面 URL (window.location.href) 传递给 php 变量 $_REQUEST['url']。我做错了什么?

Counter.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

index.php

<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/'.$_SERVER['REQUEST_URI']; // the path to the file
$file = '_Counter.txt'; // the number of vote is saved here
$file_path = $path.'_Counter.txt'; // the number of vote is saved here
if (!file_exists($file)) { // if the file does not exist, it will be created
    fopen($file, "w"); } // open file for writing only
    $count = file_get_contents($file_path); // reads entire file into a string
    if ($count == null){$count = 0;} // if the file empty, set count 0
?>
<button class="Counter-trigger">vote</button>
<span id="Counter-count">'.$count.'</span> times<br>
<div id="ClapsCounter-message"></div>
<script async src="./lib/Counter/Counter.js"></script>

console.log:

通知:未定义索引:/var/www/dist/lib/Counter/CounterReq.php 中的 url 在第 5

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

    注意:未定义索引:第 5 行 /var/www/dist/lib/Counter/CounterReq.php 中的 url

    该通知意味着您正在查找不存在的关联数组中的索引。
    让我们解决这个问题。

    将您要发送的数据存储在FormData 对象中。

    let url = window.location.href;
    const data = new FormData()
    data.set('url', url);
    

    将您的“内容类型”修改为'multipart/form-data' 或将其全部删除。 FormData 实例会自动设置正确的标头。

    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    

    通过.send方法将数据发送到服务器。

    xhr.send(data);
    

    使用$_POST 全局数组而不是$_GET,您正在通过POST 方法发送数据,因此它将在前者中。

    您发送到服务器的数据现在已作为关联数组处理。检查url的key是否存在,如果存在则保存。

    $url = isset( $_POST['url'] ) ? $_POST['url'] : '';
    

    【讨论】:

    • 谢谢,已接受您的建议。除其他外,我删除了 //xhr.setRequestHeader('Content-Type ',' application / x-www-form-urlencoded ');它的工作正常。
    【解决方案2】:

    您需要对要发送的变量进行urlencode并命名;将帖子更改为

    let post = 'url=' + encodeURIComponent(url);
    

    它应该可以正常工作。

    编辑:我没有注意到您使用的是_GET 数组而不是_POST。正如另一个答案所说,也要进行更改。

    但是,没有必要使用 JSON; application/x-www-form-urlencoded 也可以。

    【讨论】:

    • 对不起,这是我的错误;这个问题不正确。现在:$_REQUEST['url'] 而不是 $_GET['url']
    猜你喜欢
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 2011-09-02
    • 2013-03-05
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多