部分更新当前的形式,如果目标形式有错误,否则提交的目标形式
我有这个想法了下面的脚本:部分更新当前的形式,如果目标形式有错误,否则提交的目标形式
什么脚本应该做的是,当form id="try"
通过点击提交提交按钮,它不会立即提交,而是检查是否在要提交表单的页面上出现错误。
如果出现错误,我可以通过部分更新div id =“content”显示一条错误消息,说:“对不起,您的用户操作由于意外问题而不可能实现。”
如果它没有错误(页面“try1.php”被发现并且没有运行时错误,我们提交表单并转到“try1.php”,而不是“try1”的内容。 PHP的”将被送入div id="content"
HTML:
<div id="content">
THIS IS THE DIV: "content"
</div><br>
<form id="try" action= "try1.php" method="post">
<input type="submit" value="Try">
</form>
的jQuery:
$(document).ready(function()
{
$("#try").submit(function(e)
{
e.preventDefault();
// get the action
var action = $(this).attr("action");
$("#content").load(action, function()
{
//if the action is loaded to the <div id="content"> without any errors:
document.getElementById("try").submit();
//else if the target page has an error:
$("#content").html("Sorry, your user action is currently not possible due to an unexpected issue");
});
})
});
我是jQuery的新手,你有什么建议我怎么做if else语句? jQuery是正确的使用或有其他解决方案吗?
在此先感谢。
改变形式提交按钮到正规的按钮会有所帮助,因为做这个按钮调用一个函数会做的伎俩,如:
<form id="try" action= "try1.php" method="post">
<input type="button" value="Try" id="submitButton"/>
</form>
然后在JavaScript部分:
$(document).ready(function()
{
$("#submitButton").click(function(e)
{
e.preventDefault();
// get the action
var action = $("#try").attr("action");
$("#content").load(action, function()
{
//if the action is loaded to the <div id="content"> without any errors:
document.getElementById("try").submit();
//else if the target page has an error:
$("#content").html("Sorry, your user action is currently not possible due to an unexpected issue");
});
})
});
希望它解决了这个问题。有关更多说明,请发表评论。
我在我的解决方案中需要的是if else语句来检查“try1.php”是否有错误或者没有任何错误。然后,我现在可以决定是否部分更新div或提交表单。 – tca
基本上你在JavaScript中做的很好,它只是需要在答案中提到的一个调整。但是,为什么你需要确定? –
欢迎来到StackOverflow!这是一个非常好的尝试,而且你肯定沿着正确的方向使用JavaScript/jQuery进行客户端验证。 (if($(“#content”))。load();在if/else条件中,检查表单中的错误(如if ());} else {$(“#content”)。html ...})) –
我不明白为什么'action应该在每个用户提交时检查一个表单的参数...动作(动作)(提交表单的目的地)是动态的吗?然后提交一个.html文件的表单似乎没用,最好是.php,我想。 –
@LouysPatriceBessette谢谢!你是对的,最好使用.php而不是.html作为action参数中的样本值。 – tca