【发布时间】:2021-12-24 02:25:37
【问题描述】:
我有一个 XMLHttpRequest 来与服务器端 .php 文件 (clientserver.php) 进行通信。请求是这样的,
tablink = tab.url;
$("#p1").text("Selected URL - "+tablink);
var xhr=new XMLHttpRequest();
params="url="+tablink;
// alert(params);
var markup = "url="+tablink+"&html="+document.documentElement.innerHTML;
xhr.open("POST","http://localhost/WebExt/clientServer.php",false);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
//alert(xhr.responseText);
$("#div1").text(xhr.responseText);
return xhr.responseText;
clientserver.php 包含,
<?php
header("Access-Control-Allow-Origin: *");
$site=$_POST['url'];
$decision=exec("python test.py $site 2>&1");
echo $decision;
?>
当我执行上面的代码时,它会显示类似的错误
主线程上的同步 XMLHttpRequest 已被弃用,因为它对最终用户的体验产生不利影响
如何解决? 是否有任何替代代码(如 fetch API)来完成此任务(XMLHttpRequest)?
【问题讨论】:
-
“还有其他选择吗...?” - 是的。它已经在您的问题中:Fetch API
-
错误消息只是告诉您 同步 请求已被弃用 - 因此您不一定需要将整个方法切换到其他方法,而只需使请求异步反而。通过将
false作为open方法的第三个参数传递,您明确指定需要同步请求。 -
From the document by mozilla 只需从
request.open()中删除false。
标签: javascript php xmlhttprequest fetch-api web-development-server