首页 > 解决方案 > 将表单值从 javascript 传递到 wordpress

问题描述

我知道我可以从 WordPress/PHP 获取发布数据并使用 AJAX 将其传递给 JS。但是有可能反过来做吗?即在表单上创建一个 JS 事件侦听器并将值传递回服务器以使用 PHP 函数执行。

标签: javascriptphpajaxwordpress

解决方案


是的,肯定的。您几乎自己回答了这个问题。这里有一些代码可以帮助您入门。

document.querySelector(".whateverFormSubmit").click(function(e){
  e.preventDefault();
  let formInfo = document.querySelector("input1");
  let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.querySelector("response").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "ajax.php", true);
  xhttp.send('formInfo=' + formInfo);
})

注意 preventDefault(),如果你不使用它,你的表单将通过 HTTP 正文发布,从而使你的 AJAX 无用。

就这样,您在不刷新页面的情况下将信息从前端发布到后端。当然,您可以随意发送 JSON,但我保持简单。


推荐阅读