javascript - 将表单值从 javascript 传递到 wordpress
问题描述
我知道我可以从 WordPress/PHP 获取发布数据并使用 AJAX 将其传递给 JS。但是有可能反过来做吗?即在表单上创建一个 JS 事件侦听器并将值传递回服务器以使用 PHP 函数执行。
解决方案
是的,肯定的。您几乎自己回答了这个问题。这里有一些代码可以帮助您入门。
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,但我保持简单。
推荐阅读
- javascript - 如何在加载时使图像模糊,并在完全加载后使其清晰?
- c# - 字符串格式化意外结果
- javascript - 如果要拆分的字符串来自文本文件,则 split() 不起作用
- flutter - Dart:对泛型类型进行类扩展的类型推断
- spring - SendShortMessageRequest 及其任何超类对此上下文都是已知的
- sql-server - SQL Server 数据库迁移助手:无法连接到服务器
- google-cloud-platform - 如何使用 Google 的 AutoML 进行 OCR
- sql - 从 Fastreport 查询将值写入 SQL 数据库
- typescript - 使用 TypeScript 的互斥类型不正确
- google-analytics - GA 测量协议跟踪事件,但不跟踪增强型电子商务购买