使用 Fetch API 和 PHP 文件获取文本响应
Getting a text respons using Fetch API and a PHP file
我正在点击一个 php 文件,响应 return 是一个字符串。我找不到有关如何处理此问题的文档。
来自 google 开发者文档 google developer doc,我的提取很简单
fetch('upvotes.php')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
和PHP
<?php
function test(){
return "This is a test";
}
echo test();
?>
假设这在 response.json()
上失败了,因为我 return 只是一个字符串。如果我只注销响应(附上的屏幕截图),我会得到一些我不知道如何使用的东西,而且我无法转换它。 PHP 中的 return 值在哪里?
response.json
导致可怕的 Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
如何从PHP取值?
您的 PHP 没有返回 JSON,它只是返回一个字符串,因此请改用 .text()
。
我正在点击一个 php 文件,响应 return 是一个字符串。我找不到有关如何处理此问题的文档。
来自 google 开发者文档 google developer doc,我的提取很简单
fetch('upvotes.php')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
和PHP
<?php
function test(){
return "This is a test";
}
echo test();
?>
假设这在 response.json()
上失败了,因为我 return 只是一个字符串。如果我只注销响应(附上的屏幕截图),我会得到一些我不知道如何使用的东西,而且我无法转换它。 PHP 中的 return 值在哪里?
response.json
导致可怕的 Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
如何从PHP取值?
您的 PHP 没有返回 JSON,它只是返回一个字符串,因此请改用 .text()
。