英文:
I am passing javascript variable to php using fetch api method post but in php file i am getting error: undefined array key 'data'. How to fix it?
问题
<html>
<body>
<textarea id="my-textarea"> </textarea>
<button onclick="_post_text_area_()" id="submit-btn">提交</button>
</body>
<html>
# 获取文本框的值
var textarea = document.getElementById("my-textarea");
function _post_text_area_() {
var data = textarea.value;
# 在控制台显示文本框的值
console.log(data);
# 使用 fetch API 的 POST 方法传递 data 变量
fetch('_process.php', {
method: 'POST',
body: 'data=' + data
})
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data);
});
}
<?php
$data = $_POST['data'];
echo "接收到的数据: " . $data;
?>
在 _process.php 文件中出现了错误:未定义数组键 'data'。我认为,我之所以出现这个错误,是因为我的 JavaScript 函数无法创建 POST 请求,但我不知道为什么会出现这个错误。
我尝试过不同的技巧,比如使用 Ajax XmlHttpRequest 来将 data 变量传递给 _process.php 文件,但我仍然得到了相同的错误。
<details>
<summary>英文:</summary>
**------html code------**
<html>
<body>
<textarea id="my-textarea"> </textarea>
<button onclick="post_text_area()" id="submit-btn">Submit</button>
</body>
<html>
**------javascript code------**
get value of textarea
var textarea = document.getElementById("my-textarea");
function post_text_area() {
var data = textarea.value;
# show textarea value to console
console.log(data);
# pass data variable using fetch api POST method
fetch('_process.php', {
method: 'POST',
body: 'data=' + data
})
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data);
});
}
**--- _process.php ---**
<?php
$data = $_POST['data'];
echo "Received data: " . $data;
?>
I am getting an error in _process.php file: Undefined array key 'data'. I think, i am getting this error because my javascript function is not able to create post request but I don't know the exact reason why i am getting this error.
I have tried different technique like ajax XmlHttpRequest to pass data variable to _process.php file but i got the same error.
var textarea = document.getElementById("my-textarea");
var submitBtn = document.getElementById("submit-btn");
submitBtn.addEventListener("click", function() {
var data = textarea.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText); // Print the response from the server
}
};
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("data=" + data);
});
</details>
# 答案1
**得分**: 0
以下是翻译好的部分:
```javascript
const d = document;
d.addEventListener('click', e => {
if (e.target instanceof HTMLButtonElement && e.target.id === 'submit-btn') {
let fd = new FormData();
fd.set('data', d.getElementById("my-textarea").value);
fetch('_process.php', { method: 'post', body: fd })
.then(r => r.text())
.then(console.log)
.catch(alert);
}
});
<textarea id="my-textarea"></textarea>
<button id="submit-btn">Submit</button>
英文:
It is generally preferred to use FormData
when creating the payload to send via fetch
- the following does send the AJAX request but fails due to Sandbox limitations.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const d=document;
d.addEventListener('click',e=>{
if( e.target instanceof HTMLButtonElement && e.target.id=='submit-btn' ){
let fd=new FormData();
fd.set('data', d.getElementById("my-textarea").value );
fetch('_process.php', {method:'post',body:fd })
.then(r=>r.text())
.then(console.log)
.catch(alert)
}
});
<!-- language: lang-html -->
<textarea id="my-textarea"></textarea>
<button id="submit-btn">Submit</button>
<!-- end snippet -->
答案2
得分: 0
原先发布的代码只有在适当设置内容类型时才能正常工作。$_POST
变量之所以为空是因为这个原因。
您可以将您的 fetch
命令更改为以下版本:
fetch('_process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'data=' + data
})
.then(...)
...
或者,您可以在 fetch
命令中使用 application/json
内容类型:
fetch('_process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: 'data=' + data
})
.then(...)
...
... 并且在您的 PHP 代码中,不再依赖于 $_POST
对象,而改为执行以下操作:
<?php
$postedData = json_decode(file_get_contents('php://input'), true);
$data = $postedData['data'];
echo "Received data: " . $data;
只提供代码部分的翻译。
英文:
The same code that was originally posted will only work with you set the content type appropriately. The $_POST
variable was left empty for that reason.
You can change your fetch
command to the following version:
fetch('_process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'data=' + data
})
.then(...)
...
Or, you can use the application/json
content type in your fetch
command:
fetch('_process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: 'data=' + data
})
.then(...)
...
... and in your PHP, instead of relying on the $_POST
object, you do the following instead:
<?php
$postedData = json_decode(file_get_contents('php://input'), true);
$data = $postedData['data'];
echo "Received data: " . $data;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论