tru*_*pti 10 fetch urlfetch fetch-api
我正在尝试使用fetch()API POST方法来获取PHP中的POST数据.
这是我尝试过的:
var x = "hello";
fetch(url,{method:'post',body:x}).then(function(response){
return response.json();
});
Run Code Online (Sandbox Code Playgroud)
PHP:
<?php
if(isset($_GET['x']))
{
$get = $_GET['x'];
echo $get;
}
?>
Run Code Online (Sandbox Code Playgroud)
它是否正确?
Sal*_*lva 15
这取决于:
如果需要$_GET['x'],您需要在查询字符串中发送数据:
var url = '/your/url?x=hello';
fetch(url)
.then(function (response) {
return response.text();
})
.then(function (body) {
console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
如果您愿意$_POST['x'],您需要将数据发送为FormData:
var url = '/your/url';
var formData = new FormData();
formData.append('x', 'hello');
fetch(url, { method: 'POST', body: formData })
.then(function (response) {
return response.text();
})
.then(function (body) {
console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
Raf*_*jía 12
显然,当使用Fetch API将数据发送到PHP服务器时,您必须处理与您习惯的请求略有不同的请求.
您正在"POST"或"GETting"的数据在超级全局变量中不可用,因为此输入不是来自 多部分数据表单或application/x-www-form-urlencoded
您可以通过阅读特殊文件获取数据:php://input例如,使用file_get_contents('php://input')然后尝试解码该输入json_decode().
希望它有所帮助.
你可以在这里阅读更多相关内容:
https://codepen.io/dericksozo/post/fetch-api-json-php
我使用MDN 中的 postData 函数:
/**
* send_body___receive_response.js
*
* Can of-course be in <script> tags in HTML or PHP
*/
async function postData( url='', data={ } ) {
// *starred options in comments are default values
const response = await fetch(
url,
{
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "same-origin", // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json", // sent request
"Accept": "application/json" // expected data sent back
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify( data ), // body data type must match "Content-Type" header
},
);
return response.json( ); // parses JSON response into native JavaScript objects
}
const data = {
'key1': 'value1',
'key2': 2
};
postData( 'receive_body___send_response.php', JSON.stringify( data ) )
.then( response => {
// Manipulate response here
console.log( "response: ", response ); // JSON data parsed by `data.json()` call
// In this case where I send entire $decoded from PHP you could arbitrarily use this
console.log( "response.data: ", JSON.parse( response.data ) );
} );
Run Code Online (Sandbox Code Playgroud)
你可以只发布数据,但我喜欢收到它成功的响应。
/**
* receive_body___send_response.php
*/
/* Get content type */
$contentType = trim($_SERVER["CONTENT_TYPE"] ?? ''); // PHP 8+
// Otherwise:
// $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
/* Send error to Fetch API, if unexpected content type */
if ($contentType !== "application/json")
die(json_encode([
'value' => 0,
'error' => 'Content-Type is not set as "application/json"',
'data' => null,
]));
/* Receive the RAW post data. */
$content = trim(file_get_contents("php://input"));
/* $decoded can be used the same as you would use $_POST in $.ajax */
$decoded = json_decode($content, true);
/* Send error to Fetch API, if JSON is broken */
if(! is_array($decoded))
die(json_encode([
'value' => 0,
'error' => 'Received JSON is improperly formatted',
'data' => null,
]));
/* NOTE: For some reason I had to add the next line as well at times, but it hadn't happen for a while now. Not sure what went on */
// $decoded = json_decode($decoded, true);
/* Do something with received data and include it in response */
// dumb e.g.
$response = $decoded['key2'] + 1; // 3
/* Perhaps database manipulation here? */
// query, etc.
/* Send success to fetch API */
die(json_encode([
'value' => 1,
'error' => null,
'data' => null, // or ?array of data ($response) you wish to send back to JS
]));
Run Code Online (Sandbox Code Playgroud)
请记住,$_POST在 PHP 中仅获取formData()或urlSearchParams()数据,对于其他所有类型的数据,尤其是从其他文件导入的数据或外部 api 数据,您必须遵循以下步骤。
脚步:
file_get_contents(php://input)接收php中的数据json_decode($data)
在读/写数据库后使用 and finally 对其进行解码json_encode($response)。这很容易 :-))
如果碰巧您需要使用现有的服务器,它是用 $_POST 编码的,并且期望来自普通表单的参数,而不是编码为 JSON,您可以使用 formdata,这正是模拟表单。
let fd = new FormData();
fd.append("var1", val)
fd.append("var2", "Hello World");
fetch('/servers/server.php', {method: "POST", body: fd})
Run Code Online (Sandbox Code Playgroud)
这样,您的服务器将收到 POST 字段,就像它们来自普通表单输入字段一样。
$var1 = $_POST['var1']; $var2 = $_POST['var2'];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15173 次 |
| 最近记录: |