簡體   English   中英

如何在沒有 JQUERY 的情況下從瀏覽器擴展向 localhost 發出 POST 請求?

[英]How to do a POST request from a browser extension to localhost WITHOUT JQUERY?

這類問題已經被問過很多次了,但我找不到答案:

  1. 不使用 jQuery

  2. 作品

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

不是 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的(在函數中處理)或 boolean。

這就是我嘗試使用 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 編碼的數據)沒有意義。 您正在任意混合兩種不同的數據格式。 您還沒有設置需要的內容類型 header,否則它默認為純文本/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
}

PS $_POST["log_item"]=urldecode($_POST["log_item"]); 在 PHP 中是多余的 - 數據已經自動解碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM