gpt4 book ai didi

javascript - onBlur触发的多个表单字段如何使用JS fetch api系统替换jQuery AJAX系统?

转载 作者:行者123 更新时间:2023-12-02 21:14:59 24 4
gpt4 key购买 nike

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

2年前关闭。




Improve this question




我有大约 160 个表单字段(在选项卡式表单上),类似于:

<form id="7" name="7" action="#" method="post">
<input type="text" id="houseName" name="houseName" value="<?=$existingValue[0]['houseName']?>
<input type="text" id="streetName" name="streetName" value="<?=$existingValue[0]['streetName']?>
...
</form>

我正在尝试这样做,以便当用户从文本字段中输入或删除数据,然后获取字段的焦点时,新字段值由 fetch api 发送到服务器上的 php 以进行检查,如果通过,插入到数据库中。服务器 php 将发送返回以确认或提醒用户数据因检查失败而被接受或拒绝。

一旦返回返回,我希望它能够为相关的 input 添加一个类字段并添加一个 html span具有两个特定类之一,具体取决于正在处理的数据的成功或失败。

我在理解 fetch api 系统的工作原理时遇到了很大的困难,并且未能成功。我花了很多时间阅读,但找不到任何关于如何构建 fetch api 调用来为我的最终结果工作的直接解释或示例。许多在线文档似乎对如何使用 php 目标略有冲突。例如:
fetch("//127.0.0.1/collect/post.2.php")

或者
fetch("./collect/post.2.php")    

是否必须从 JS 代码调用完整的 url,或者可以通过相对于服务器的本地路径来完成(因为它以前在我试图替换的旧 jQuery/AJAX 版本上)?

获取代码可以驻留在像 app.2.js 这样的单独文件中并在 html 文档的头部调用,还是必须内联?

post.2.php 中的 php 代码是否需要特定格式才能与 fetch 一起使用?

这可以通过所有输入字段的一段 fetch api 代码来完成,还是每个输入字段都需要一个单独的代码块?

请耐心等待——我不年轻,没有简单的英语例子,学习这些东西并不容易。他们似乎都假设每个人都处于经验丰富的水平!我不是在找人给我写代码-我想学习,但是非常感谢带有一些简单解释的代码示例。谢谢。

编辑

根据 ADyson 的请求,这是执行 ajax 操作的先前代码:
function blurHandler() {
var id = this.id;
$.post('./collect/post.2.php?data=' + secData, $('#'+id).serialize(), function(data) {
$("#errorText_"+id).html(data['errorText_'+id]);
$("#resultImg_"+id).html(data['resultImg_'+id]);
}, 'json' );
}

我相信这依赖于 html header 中的以下行:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

这是在服务器端启动的 php 示例。数据库处理中使用的 xID 值是从“data=”字符串中推断出来的。
    if(isset($_POST['houseName'])) {
$userInput = $_POST['houseName'];
if(trim($userInput) == "") { $userInput = NULL; }
try {
$stmt = $conn->prepare("UPDATE $database.table01 SET `houseName` = :userinput WHERE `xID` = :xid");
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 32);
$stmt->bindParam(':xid', $xID, PDO::PARAM_INT, 11);
$stmt->execute();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
$report_name = array();
if($userInput == NULL) {
$report_name['errorText_houseName'] = "This field cannot be left blank";
$report_name['resultImg_houseName'] = "<img src=\"./img/form_boo.gif\" class=\"resultImg\" alt=\"&#10008;\" title=\"&#10008;\">";
} else {
$report_name['errorText_houseName'] = NULL;
$report_name['resultImg_houseName'] = "<img src=\"./img/form_yay.gif\" class=\"resultImg\" alt=\"&#10004;\" title=\"&#10004;\">";
}
echo json_encode($report_name);
}

尽管功能齐全,但这一切都相当古老。我不知道如何将此功能转换为使用 fetch api。

最佳答案

您可以使用FormData为了这。

Fetch API的URL解析算法与 AJAX 完全相同。

Fetch API 使用 Promises使用 ECMAscript 2015 Language Specification 引入 JavaScript . XMLHttpRequest 使用回调;这就是为什么它们看起来如此不同。

切换到 Fetch API 后无需修改后端代码。

请更新表单输入,如下所示:

<form id="7" name="7" action="#" method="post">
<input type="text" id="houseName" name="houseName" onblur="blurHandler(this)" value="<?=$existingValue[0]['houseName']?>
<input type="text" id="streetName" name="streetName" onblur="blurHandler(this)" value="<?=$existingValue[0]['streetName']?>
...
</form>

下面的代码将模糊输入及其值作为虚拟表单的单个成员提交。

function blurHandler(input) {
const id = input.id;

// Create a new FormData instance
const formData = new FormData();

// Append the input into FormData
formData.append(input.name, input.value);

// Now we perform the POST
fetch(`./collect/post.2.php?data=${secData}`, {
method: 'POST',
body: formData, // Fetch API can deal with FormData instances automatically
})
.then((response) => response.json()) // Parse server response as JSON
.then((data) => { // Parsed JSON passed as `data`
document.getElementById(`errorText_${id}`).innerHTML = data[`errorText_${id}`];
document.getElementById(`resultImg_${id}`).innerHTML = data[`resultImg_${id}`];
})
.catch((error) => {
// Trace the error and pop an alert if anything goes wrong
console.trace(error);
alert('Failed to submit form');
});
}

关于javascript - onBlur触发的多个表单字段如何使用JS fetch api系统替换jQuery AJAX系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60995637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com