返回响应而不是 PHP 中的源代码

时间:2021-04-10 06:02:48

标签: javascript php html

我有代码在 fetch 中使用 javascript 来获取远程 url 的 html 源。代码是:


<!DOCTYPE html>
<html>
<body>
<p id="output"></p>
<script>
function getRandomDifferent(arr, last = undefined) {
  if (arr.length === 0) {
    return;
  } else if (arr.length === 1) {
    return arr[0];
  } else {
    let num = 0;
    do {
      num = Math.floor(Math.random() * arr.length);
    } while (arr[num] === last);
    return arr[num];
  }
}
  

const arr = ['https://gdrivex.github.io','https://gdrivex.github.io','https://gdrivex.github.io','https://gdrivex.github.io'];
const r1 = getRandomDifferent(arr);

fetch (r1)
.then(x => x.text())
.then(y => document.getElementById("output").innerHTML = y);

</script>
</body>
</html>

现在上面的代码完美地返回了外部 url 的来源。现在,当我在 php 中使用 file_get_contents 获取使用上面托管在 .html 页面上的代码检索的内容时,返回我上面的代码本身,而我想获取检索的代码而不是正在尝试的代码检索。此外,我不能直接将 file_get_contents 用于要检索的源代码。我可以在 php 中做些什么来检索代码吗?

1 个答案:

答案 0 :(得分:1)

您可以创建一个 javascript 函数来使用 XMLHttpRequest object 将数据发送到服务器:

function sendData(someDataString) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "https://example.com/pathToPhpFile/fileName.php", true);
    xhttp.send(someDataString);
}

您可以在此处阅读更多信息:MDN XMLHttpRequest

您还可以通过将其添加到您的函数中来检查服务器是否确认收到了数据:

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
};

您将通过回显从 PHP 文件发送确认。

相关问题