【发布时间】:2021-05-26 07:04:17
【问题描述】:
这类问题已经被问过很多次了,但我找不到答案:
-
不使用 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。
【问题讨论】:
-
你试过
xhttp.send(info);吗?您在那里所做的事情(在 JSON 对象中发送 URL 编码的数据)毫无意义。 -
附言。如果您希望使用本机浏览器功能执行 Ajax,XMLHttpRequest 的现代替代方法是 fetch()。 developer.mozilla.org/en-US/docs/Web/API/Fetch_API 。它支持 Promises(就像 jQuery 一样),并且语法总体上更清晰。
-
但它是否适用于 jquery?检查开发工具上的网络选项卡以检查错误。
-
@ADyson:您能否发布关于我如何使用您的第一条和第二条评论中的解决方案的答案?我都试过了,但似乎无法让它们工作。
-
@ariel:它确实适用于 jQuery(我只是因为你的要求才添加它),并且在任何一种情况下都没有错误:使用或不使用 jQuery。如果没有 jQuery,它会完成 XHR,但不会记录任何内容,而使用 jQuery,它会记录所有内容。
标签: javascript php xmlhttprequest browser-extension