Ajax,通过使用指向同一页面的链接提交表单

Ajax, submitting form by using a link to the same page

本文关键字:一页 链接 表单 提交 Ajax      更新时间:2023-09-26

首先,我有一个表格,我可以用该代码提交它:

<form method="post" action="javascript:void(0);" id="productFrom<?php echo $x;?>">
    <input type = "hidden" value="<?php echo $MenuItem['Item_ID']?>" name="I_ID" />
    <input type = "hidden" value="<?php echo $MenuItem['Item_Name']?>" name="I_Name" />
    <input type = "hidden" value="<?php echo $MenuItem['Item_Price']?>" name="I_Price" />
    <input type = "hidden" value="<?php echo $MenuItem['Item_Image']?>" name="I_img" />
</form>
<a class="view-link shutter" href="javascript: submitForm('<?php echo $x;?>');" name="Add">
<i class="fa fa-plus-circle"></i>Add To Cart</a>

<script type="text/javascript">
function submitForm(formID)
    {
        $('#productFrom'+formID ).submit();
    }
</script>

但是我需要将其提交到同一页面并在特定的div中打印表单内容使用id"CART",所以我必须使用ajax

我试过这个,但不起作用

<script type="text/javascript">
function submitForm(formID) {
    $('#productFrom'+formID ).submit(function(){
        var str = $(this).serialize();
        $.ajax('getCartItems.php', str, function(result){
            // the result variable will contain any text echoed by getCartItems.php
            document.getElementById('CART').innerHTML = alert(result);
        }
        return(false);
    }););
}
</script>

我的错误是:

*SyntaxError: missing ) after argument list //on return false line
*ReferenceError: submitForm is not defined

当代码格式正确时,更容易看到语法错误的位置:

function submitForm(formID)
{
    $('#productFrom' + formID).submit(function () {
        var str = $(this).serialize();
        $.ajax('getCartItems.php', str, function (result) {
            // the result variable will contain any text echoed by getCartItems.php
           $('#CART').html(result);
        });
        return false;
    });  
}