[英]Ajax pass parameter in data send to php
假设我有一个带有 onclick 函数的元素,它在单击时触发 prompt()。 一旦用户填写提示,它也会触发一个ajax请求,将带有post类型的提示值发送到php页面以获得响应。
所以我有这个代码:
<i class="fas fa-wrench text-warning editmode" id="Pseudo" onclick="goEdit(this.id)" title="Edit my pseudo"></i>
function goEdit(id) {
console.log(id); // The console log here print me "Pseudo" and that's what i want
$(document).ready(function() {
let userchange = prompt();
$.ajax({
type: 'POST',
url: 'traitements/traitement-profil.php',
data: {
id: userchange
// The problem is here ! I want to send a $_POST['Pseudo'] that contains the answer of the prompt.
// But that doesn't work.
// Instead if i a do a print($_POST) in my php page i get this as a response in my alert below:
// array(1) { ["id"]=> array(1) { ["id"]=> string(24) "Answer of the prompt here"
},
dataType: 'text',
success: function(data) {
alert(data);
}
});
});
}
我需要我的 $_POST 等于点击按钮的 id 值的原因是因为我需要在同一页面上有多个像这样的按钮,每个按钮都有自己的用途,但总是会做一些同样的事情。 只有 $_post 参数会为每个而更改,并且此参数必须等于单击按钮的 id
更新:如果您想要的是数据对象中的动态键,您可以通过以下方式实现:
var data = {};
data[id] = userchange;
$.ajax({
type: 'POST',
url: 'traitements/traitement-profil.php',
data: data,
dataType: 'text',
success: function(data) {
alert(data);
}
});
您似乎误解了如何构造JSON 对象。
您传递的数据应如下所示:
data: {
id: id,
answer: userchange
},
然后在 PHP 中,您将能够通过以下方式访问它们:
$_POST['id'] // contains "Pseudo"
$_POST['answer'] // contains "Answer of the prompt here"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.