英文:
How can I call a jQuery function AFTER a form is submitted?
问题
如何在表单提交后调用jQuery函数?
我知道如何在提交时调用函数,但我想在提交后并且使用PHP将详细信息添加到数据库后再调用它。
我正在制作一个用户可以将商品放入购物车的网站。这部分运行良好。然而,在将产品发布并添加到购物车后,我想显示一个弹出框来显示购物车。因此,我需要在提交完成后调用该函数。
英文:
How do I call a jQuery function AFTER a form is submitted?
I know how to call a function ON submit, but I want to call it after the post is submitted and details are put into the database with PHP.
I'm making a website where the user can put items into a cart. This works fine. However, AFTER a product is posted and added into the cart I want to display a popup-box displaying the cart. Hence I need the function to be called AFTER the submit has completed.
答案1
得分: 1
你可以从done()
函数中实现这一点,例如,假设你的表单和Ajax请求如下所示:
$("#target").on("submit", function(event) {
event.preventDefault();
var theId = $("input[name='id']", this).val();
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : theId },
dataType: "json"
});
request.done(function(serverData) {
showCart(serverData);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
由于Ajax请求默认是异步的,而且应该是异步的,所以当Ajax请求成功时,showCart()
函数将被调用。
有关更多详细信息,请查看文档。
英文:
> Hence I need the function to be called AFTER the submit has completed.
You can do that from done()
, for example, assuming your form and Ajax request are like this:
<form id="target" action="#">
<input type="text" id="id" value="1">
<input type="submit" value="Go">
</form>
$( "#target" ).on( "submit", function( event ) {
event.preventDefault();
var theId = $("input[name='id']",this).val();
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : theId },
dataType: "json"
});
request.done(function( serverData ) {
showCart(serverData);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
//....
function showCart(dataForCart) {
//Use dataForCart if needed and show cart
}
Since Ajax requests are asynchronous by default and should be, showCart()
will be called when the Ajax request has succeeded.
For more details, check the documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论