我大约有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
字段中,并添加span
带有两个特定类之一的html ,具体取决于正在处理的数据的成功或失败。
我在理解fetch api系统的工作方式时遇到了很大的麻烦,但未能成功。我已经花了很多时间阅读,但是找不到任何直接的解释或如何构造访存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一起使用?
可以使用一个针对所有输入字段的提取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标头中的以下行:
<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=\"✘\" title=\"✘\">";
} else {
$report_name['errorText_houseName'] = NULL;
$report_name['resultImg_houseName'] = "<img src=\"./img/form_yay.gif\" class=\"resultImg\" alt=\"✔\" title=\"✔\">";
}
echo json_encode($report_name);
}
尽管功能齐全,但这些都相当古老。我不知道如何将此功能转换为使用访存api。
您可以为此使用FormData。
Fetch API的URL解析算法与AJAX完全相同。
Fetch API使用Promises,ECMAscript 2015语言规范将其引入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');
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句