对 PHP 文件的 XMLHttpRequest 和 Fetch 请求不起作用 Svelte
XMLHttpRequest and Fetch request to PHP file not working Svelte
我无法使用 Svelte 从外部主机上的 PHP 文件中获取信息。
不过,奇怪的是,XMLHTTP 请求在链接到 Web 上托管的文本文件时有效。
这是我的 JS 代码:
<script>
let content = "";
function httpGet()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://www.kayasuleyman.co.uk/form.php?email=example");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
content = this.responseText;
};
}
}
</script>
这里是 HTML:
<div id="demo">
<button on:click={httpGet}>Submit</button>
<p>Output: {content}</p>
</div>
我的 PHP 文件的输出,应该只是“示例”,returns 什么都没有。我被这个问题弄糊涂了,用fetch语句也不行。
有什么想法吗?
尝试将其添加到您的 php 文件的顶部:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
我无法使用 Svelte 从外部主机上的 PHP 文件中获取信息。
不过,奇怪的是,XMLHTTP 请求在链接到 Web 上托管的文本文件时有效。
这是我的 JS 代码:
<script>
let content = "";
function httpGet()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://www.kayasuleyman.co.uk/form.php?email=example");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
content = this.responseText;
};
}
}
</script>
这里是 HTML:
<div id="demo">
<button on:click={httpGet}>Submit</button>
<p>Output: {content}</p>
</div>
我的 PHP 文件的输出,应该只是“示例”,returns 什么都没有。我被这个问题弄糊涂了,用fetch语句也不行。
有什么想法吗?
尝试将其添加到您的 php 文件的顶部:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");