所以我使用 instascan api 扫描二维码,并假设将扫描的内容发送到我的 php 文件,但无论我使用 POST 还是 GET,它都不会在 php 文件中读取它们并说出来应该在 php 中接收 POST 或 GET 这是我的js代码:
var app = new Vue({
el: '#app',
data: {
scanner: null,
activeCameraId: null,
cameras: [],
scans: []
},
mounted: function () {
var self = this;
self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5 });
self.scanner.addListener('scan', function (content, image) {
self.scans.unshift({ date: +(Date.now()), content: content });
self.sendToPHP(content); // Call function to send content to PHP file
});
Instascan.Camera.getCameras().then(function (cameras) {
self.cameras = cameras;
if (cameras.length > 0) {
self.activeCameraId = cameras[0].id;
self.scanner.start(cameras[0]);
} else {
console.error('No cameras found.');
}
}).catch(function (e) {
console.error(e);
});
},
methods: {
formatName: function (name) {
return name || '(unknown)';
},
selectCamera: function (camera) {
this.activeCameraId = camera.id;
this.scanner.start(camera);
},
sendToPHP: function (content) {
var self = this;
var url = 'Table.php?content=' + encodeURIComponent(content);
fetch(url, {
method: 'GET'
})
.then(function(response) {
if (response.ok) {
console.log('Content sent to PHP successfully');
return response.text();
} else {
console.error('Error sending content to PHP');
throw new Error('Error sending content to PHP');
}
})
.then(function(data) {
// Handle response from PHP if needed
console.log(data);
})
.catch(function(error) {
console.error('Error:', error);
});
}
}
});
在此 js 代码中,我尝试通过 GET 发送内容变量
这是我的 php 代码:
<?php
// Check if the request method is GET
if ($_SERVER["REQUEST_METHOD"] === "GET") {
// Debug: Output the entire $_GET array
var_dump($_GET);
// Check if the 'content' parameter exists in the query string
if (isset($_GET['content'])) {
// Retrieve the scanned content from the query string
$content = $_GET['content'];
echo "Scanned content received via GET: " . $content;
// could save the scanned content to a database
} else {
// If 'content' parameter is missing in the query string
echo "Error: 'content' parameter is missing in the query string.";
}
} else {
// If the request method is not GET
echo "Error: This endpoint only accepts GET requests.";
}
?>
这个 php 代码是我应该从内容变量接收数据的地方,但它总是回显消息“错误:此端点仅接受 GET 请求。”
我使用 xampp 在 localhost 中打开我的文件,并且我多次交替使用 POST 和 GET 方法来使此代码正常工作,但总是给出相同的消息。 php 中这段代码的目标是我想将最新扫描的内容发送到我的数据库,以检查该扫描是否存在于我的数据库的表中,所以我想在连接到我的数据库之前尝试一下,看看它是否只是发送数据。
编辑:这是我的 html 页面中 Table.php 请求屏幕截图中的响应:
就这样做,因为你不需要检查请求方法,检查 $_GET 就已经做到了。
if (isset($_GET['content'])) {
// Retrieve the scanned content from the query string
$content = $_GET['content'];
echo "Scanned content received via GET: " . $content;
// could save the scanned content to a database
} else {
// If 'content' parameter is missing in the query string
echo "Error: 'content' parameter is missing in the query string.";
}