微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在没有 JQUERY 的情况下从浏览器扩展向本地主机发出 POST 请求?

如何解决如何在没有 JQUERY 的情况下从浏览器扩展向本地主机发出 POST 请求?

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

  1. 不使用 jQuery

  2. 作品

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

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

"Drop that and try 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 \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 中是多余的 - 数据会自动解码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。