【发布时间】:2021-11-18 20:46:59
【问题描述】:
我的异步获取函数嵌入在 names.php 中,当我激活该函数时,它会将我带到它发布到的端点:change-name.php。我想保留在 names.php 页面上,但在 fetch 函数运行后刷新该页面。
我单击下面的跨度以打开一个文本字段,在其中添加名称并单击按钮:
<span onclick="addGuestName(this)">
<button class="addPaxName btn btn-xs btn-warning">ADD</button>
这工作得很好。并更新名称,但单击 ADD 按钮后我被传送到 /change-name.php 页面。
我希望的响应是在获取功能完成后保留在原始页面上并刷新页面。 我如何得到这个结果。
async function updateGuestName(paxid,name){
paxIDbody = '{"pxid": "' + paxid + '", "name": "' + name + '"}';
console.log("PaxID:", paxIDbody);
try {
const settings = {
method: "POST",
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: paxIDbody,
};
const response = await fetch(
"/change-name.php",
settings
);
const data = await response.json();
console.log("DATA: ",data);
} catch (error) {
console.log("ERROR: ",error);
}
}
function addGuestName(obj) {
const itemClicked = obj;
const paxid = obj.id;
const addPaxName = itemClicked.nextElementSibling;
const addPaxNameButton = itemClicked.nextElementSibling;
addPaxNameButton.style.display = 'inline-block';
var addPaxNameField = document.createElement('input');
addPaxNameField.setAttribute('type', 'text');
addPaxNameField.setAttribute('name', 'visitorNameSurname[]');
addPaxNameField.setAttribute('placeholder', 'Enter Name & Surname');
itemClicked.parentNode.insertBefore(addPaxNameField, itemClicked.nextSibling);
addPaxNameField.setAttribute("required", "required");
addPaxNameButton.addEventListener('click', () => {
const name = addPaxNameField.value;
updateGuestName(paxid,name);
})
}
我的 PHP 端点在数据库更新后返回 JSON:
header('Content-type:application/json;charset=utf-8');
$myObj=new \stdClass();
$myObj->status = $status;
$myObj->message = $message;
$myJSON = json_encode($myObj);
echo $myJSON;
【问题讨论】:
-
默认按钮类型为
submit。只需使用type="button"。 -
@bigless 没办法,现在我为什么没想到! :)
-
@bigless 将此添加为您的答案,我会接受它,它已经解决了这个谜团。谢谢!
-
它是duplicate question。肯定会有与我的答案相似的问题。作为你,我会删除它以使这个地方更干净;)
-
我明白了,但这个问题是 jQuery Ajax,而不是 vanilla JS。
标签: javascript php async-await