jQuery - 合并 ajax 请求,因为它们被拆分并替换数据

jQuery - merging ajax requests as have them split up and replacing data

本文关键字:拆分 数据 替换 因为 合并 ajax 请求 jQuery      更新时间:2023-09-26

>我是 js/jquery 的新手,所以认为我做得很好,但我注意到我的代码存在问题,并认为我需要以某种方式将其合并在一起。

如果我输入电子邮件,

它会在数据库中更新,但是一旦我输入名字或姓氏,它就会更新这些,但随后会删除电子邮件......

这是到目前为止的JS:

// function to check email field, validate and save to ac for this customer session
function checkIt(field) {
    field = $(field);
    var email = field.val();
    var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
    var emailInputId = field.attr('id');
    if ($("." + emailInputId + "_error_message").length > 0) {
        $("." + emailInputId + "_error_message").remove();
    }
    //console.log($(emailInputId+"_error_message"));
    if (validEmail(email)) {
        //alert('valid email');
        $.ceAjax('request', fn_url('ac.email'), {
            method: 'post',
            data: {
                'email': email
            },
            caching: true
        });
        field.removeClass('cm-failed-field');
        field.prev().removeClass('cm-failed-label');
        field.next("span").remove();
    } else {
        field.addClass('cm-failed-field');
        field.prev().addClass('cm-failed-label');
        field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
    }
}
// lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
var field = $('#onestepcheckout .ty-billing-email input')[0];
if ($(field).length > 0) {
    if (field.value) {
        checkIt(field);
    }
}
// check email thats inputted and save to ac session for this customer, or if email changed to update
$('#onestepcheckout .ty-billing-email input').blur(function() {
    checkIt(this);
});
// if first name entered lets grab it and add to the ac session for the customer
var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
$(firstname_sel+','+lastname_sel).blur(function() {
    var firstname = $(firstname_sel).val();
    var lastname = $(lastname_sel).val();
    $.ceAjax('request', fn_url('ac.email'), {
        method: 'post',
        data: {
            'firstname': firstname,
            'lastname': lastname
        },
        caching: true
    });
});
// lets grab the first name and last name if already in input
var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
    if (firstname_sel_pre.value || lastname_sel_pre.value) {
        var firstname_pre = $(firstname_sel_pre).val();
        var lastname_pre = $(firstname_sel_pre).val();
        $.ceAjax('request', fn_url('ac.email'), {
            method: 'post',
            data: {
                'firstname': firstname_pre,
                'lastname': lastname_pre
            },
            caching: true
        });
    }
}

.PHP

if ($mode == 'email') {
//die('post was recieved from js to this controller! yippie!!');
//print_r($_POST['email']);
//die($_POST['email']);
/**************Start: Abandoned Carts *********************/
$_SESSION['cart']['user_data']['email'] = $_POST['email'];
$cartContents=mysql_escape_string(serialize($_SESSION['cart']['products']));
$shippingCost=$_SESSION['cart']['shipping_cost'];
$tax=$_SESSION['cart']['tax_summary']['total'];
$orderTotal=$_SESSION['cart']['total'];
$userFirstName=$_POST['firstname'];
$userLastName=$_POST['lastname'];
$userEmail=$_POST['email'];
$userId=$_SESSION['settings']['cu_id']['value'];
$userExpiry=$_SESSION['settings']['cu_id']['expiry'];
$date=date('Y-m-d h:i:s');
$userExist=db_get_fields("SELECT user_id FROM cscart_abandoned_cart WHERE user_id = '".$userId."'");
if($userExist) {
    db_query("UPDATE cscart_abandoned_cart SET first_name='".$userFirstName."', last_name='".$userLastName."', email='".$userEmail."', shipping='".$shippingCost."',tax='".$tax."',order_total='".$orderTotal."',cart='".$cartContents."',last_updated='".$date."',status='0' WHERE user_id='".$userId."'");
} else {
    db_query("INSERT INTO cscart_abandoned_cart (first_name,last_name,email,cart,user_id,expiry,last_updated,shipping,tax,order_total,status)values('".$userFirstName."','".$userLastName."','".$userEmail."','".$cartContents."','".$userId."','".$userExpiry."','".$date."','".$shippingCost."','".$tax."','".$orderTotal."','0')");
}
}

更新

我已经阅读了有关设置全局变量的信息,但尽我所能,有点卡住了,我将ajax请求放在一个新函数中(不确定是否正确),或者我是否正确完成,但现在有点迷茫我应该如何调用ajax函数?

// set global variables
var checkoutEmail = "";
var checkoutFirstName = "";
var checkoutLastName = "";
$(document).ready(function() {
    function fireCheckoutAC(checkoutEmail, checkoutFirstName, checkoutLastName) {
        $.ceAjax('request', fn_url('ac.email'), {
            method: 'post',
            data: {
                'email': checkoutEmail,
                'firstname': checkoutFirstName,
                'lastname': checkoutLastName
            },
            caching: true
        });
    }
    // function to check email field, validate and save to ac for this customer session
    function checkIt(field) {
        field = $(field);
        var email = field.val();
        var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
        var emailInputId = field.attr('id');
        if ($("." + emailInputId + "_error_message").length > 0) {
            $("." + emailInputId + "_error_message").remove();
        }
        //console.log($(emailInputId+"_error_message"));
        if (validEmail(email)) {
            //alert('valid email');
            checkoutEmail = email;
            field.removeClass('cm-failed-field');
            field.prev().removeClass('cm-failed-label');
            field.next("span").remove();
        } else {
            field.addClass('cm-failed-field');
            field.prev().addClass('cm-failed-label');
            field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
        }
    }
    // lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
    var field = $('#onestepcheckout .ty-billing-email input')[0];
    if ($(field).length > 0) {
        if (field.value) {
            checkIt(field);
        }
    }
    // check email thats inputted and save to ac session for this customer, or if email changed to update
    $('#onestepcheckout .ty-billing-email input').blur(function() {
        checkIt(this);
    });
    // if first name entered lets grab it and add to the ac session for the customer
    var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
    var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
    $(firstname_sel+','+lastname_sel).blur(function() {
        checkoutFirstName = $(firstname_sel).val();
        checkoutLastName = $(lastname_sel).val();
    });
    // lets grab the first name and last name if already in input
    var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
    var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
    if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
        if (firstname_sel_pre.value || lastname_sel_pre.value) {
            checkoutFirstName = $(firstname_sel_pre).val();
            checkoutLastName = $(firstname_sel_pre).val();
        }
    }
});

我制定了解决方案,这里是:

/* grab completed email when enetred into checkout and add to abandoned cart for that session */
function validEmail(v) {
    var r = new RegExp(/^(("['w-'s]+")|(['w-]+(?:'.['w-]+)*)|("['w-'s]+")(['w-]+(?:'.['w-]+)*))(@((?:['w-]+'.)*'w['w-]{0,66})'.([a-z]{2,6}(?:'.[a-z]{2})?)$)|(@'[?((25[0-5]'.|2[0-4][0-9]'.|1[0-9]{2}'.|[0-9]{1,2}'.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})'.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})']?$)/i);
    return (v.match(r) == null) ? false : true;
}
// set global variables
var checkoutEmail = "";
var checkoutFirstName = "";
var checkoutLastName = "";
$(document).ready(function() {
    function fireCheckoutAC() {
        $.ceAjax('request', fn_url('ac.email'), {
            method: 'post',
            data: {
                'email': checkoutEmail,
                'firstname': checkoutFirstName,
                'lastname': checkoutLastName
            },
            caching: true
        });
    }
    // function to check email field, validate and save to ac for this customer session
    function checkIt(field) {
        field = $(field);
        var email = field.val();
        var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
        var emailInputId = field.attr('id');
        if ($("." + emailInputId + "_error_message").length > 0) {
            $("." + emailInputId + "_error_message").remove();
        }
        //console.log($(emailInputId+"_error_message"));
        if (validEmail(email)) {
            //alert('valid email');
            checkoutEmail = email;
            fireCheckoutAC();
            field.removeClass('cm-failed-field');
            field.prev().removeClass('cm-failed-label');
            field.next("span").remove();
        } else {
            field.addClass('cm-failed-field');
            field.prev().addClass('cm-failed-label');
            field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
        }
    }
    // lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
    var field = $('#onestepcheckout .ty-billing-email input')[0];
    if ($(field).length > 0) {
        if (field.value) {
            checkIt(field);
        }
    }
    // check email thats inputted and save to ac session for this customer, or if email changed to update
    $('#onestepcheckout .ty-billing-email input').blur(function() {
        checkIt(this);
    });
    // if first name entered lets grab it and add to the ac session for the customer
    var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
    var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
    $(firstname_sel+','+lastname_sel).blur(function() {
        checkoutFirstName = $(firstname_sel).val();
        checkoutLastName = $(lastname_sel).val();
        fireCheckoutAC();
    });
    // lets grab the first name and last name if already in input
    var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
    var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
    if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
        if (firstname_sel_pre.value || lastname_sel_pre.value) {
            checkoutFirstName = $(firstname_sel_pre).val();
            checkoutLastName = $(firstname_sel_pre).val();
            fireCheckoutAC();
        }
    }
});