如何做一个POST请求从浏览器扩展到本地主机没有JQUERY?



这类问题已经被问过很多次了,但我找不到一个答案:

  1. 不使用jQuery

  2. 作品

jQuery答案:https://stackoverflow.com/a/44105591, https://stackoverflow.com/a/43393223

不是jQuery,但不工作:https://stackoverflow.com/a/38982661

"放下它,试试jQuery">

首先,我正在尝试使用浏览器扩展来实现这一点。

这是我(唯一)的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为字符串,timeundefined(在函数中处理)或布尔值。

这是我如何尝试使用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 at 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编码的数据)没有意义。您任意地混合了两种不同的数据格式。您还没有设置需要的内容类型头,否则它默认为纯文本/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中是冗余的-数据将被自动解码。

最新更新