【问题标题】:My async fetch function takes me to the endpoint I POST to. I want it to refresh the page it POSTS from我的异步获取功能将我带到我发布到的端点。我希望它刷新它发布的页面
【发布时间】: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


【解决方案1】:

默认按钮类型是提交。在onsubmit 回调中使用onsubmitevent.preventDefault()。如果不需要浏览器的表单验证,可以使用更直接的type="button"。如需刷新页面,请查看location.reload()

【讨论】:

    【解决方案2】:
    addPaxNameButton.addEventListener('click', (e) => {
        e.preventDefault();
        const name = addPaxNameField.value;
        updateGuestName(paxid,name);
      })
    

    【讨论】:

    • 虽然这可能是您应该解释答案的解决方案,所以它不仅仅是代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多