问题描述
这种类型的问题已经被问过很多次了,但我找不到答案:
-
不使用 jQuery
-
作品
jQuery 答案:https://stackoverflow.com/a/44105591、https://stackoverflow.com/a/43393223
不是 jQuery,但不起作用:https://stackoverflow.com/a/38982661
首先,我正在尝试使用浏览器扩展程序来做到这一点。
这是我的(唯一的)JS 文件:
// ...
function log(info,time){
if(time===undefined)time=true;
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
info="http://localhost/log.PHP?log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
xhttp.open("GET",info,true);
xhttp.send(null);
}
// ...
当然,这使用了 GET。 info
是一个字符串,而 time
是 undefined
(在函数中处理)或布尔值。
这就是我尝试使用 POST 的方式:
function log(info,time){
if(time===undefined)time=true;
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
info="log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
xhttp.open("POST","http://localhost/log.PHP",true);
xhttp.send(JSON.stringify({
"log_item":info,"time":time?"true":"false"
}));
}
取自https://stackoverflow.com/a/38982661
这是我的log.PHP
:
<?PHP
header("Access-Control-Allow-Origin: *");
if(isset($_POST["log_item"],$_POST["time"])){
$_POST["log_item"]=urldecode($_POST["log_item"]);
if($_POST["time"]==="true")file_put_contents("log.html","<li><b>[".date('l,F j,Y \a\t h:i:s A')."]: </b>$_POST[log_item]</li>\n",FILE_APPEND);
else file_put_contents("log.html",$_POST["log_item"]."\n",FILE_APPEND);
echo $_POST["time"];
}
不过,您不必担心。它只是登录到 log.html
。
我找不到对此的有效解决方案(或者我可能没有正确使用有效的解决方案)。再次您的答案不应包含 jQuery。
解决方法
您在那里做什么(在 JSON 对象中发送 URL 编码的数据)毫无意义。您正在任意混合两种不同的数据格式。您还没有设置 content-type 标头,这是必需的,否则默认为纯文本/HTML,服务器不会将其填充到 $_POST 变量中。
这个版本可以工作:
function log(info,time){
if(time===undefined)time=true;
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
info="log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
xhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //set content type
xhttp.open("POST","http://localhost/log.php",true);
xhttp.send(info); //just send the URL-encoded data without wrapping it in JSON
}
附言$_POST["log_item"]=urldecode($_POST["log_item"]);
在 PHP 中是多余的 - 数据会自动解码。