在Ajax中传递URL变量

时间:2016-09-21 14:28:31

标签: javascript ajax variables url

我确定我是否以正确的方式进行此操作,但我需要在URL重定向中传递表单变量。重定向正在运行,但我无法输出数据。

$("#promoForm").on('submit', function(e) {
    e.preventDefault();
    var data = {
        firstname: $("#firstname").val(),
        lastname: $("#lastname").val(),
        email: $("#email").val(),
        code: $("#code").val()
    };

    if ( isValidEmail(data['email']) && (data['firstname'].length > 1) && (data['lastname'].length > 1) && (data['code'].length > 1) ) {
        $.ajax({
            type: "POST",
            url: "php/promo.php",
            data: data,
            success: function() {
                $('.success.pf').delay(500).fadeIn(1000);
                $('.failed.pf').fadeOut(500);
                setTimeout(function() {
                  window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
                }, 3000);
            }
        });
    } else {
        $('.failed.pf').delay(500).fadeIn(1000);
        $('.success.pf').fadeOut(500);
    }

    return false;
});

2 个答案:

答案 0 :(得分:1)

试试这个,

window.location.href = "http://demo.example.com/signup?firstname="+data['firstname']+"lastname="+data['lastname']+"email"=+data['email']+"code="+data['code']

答案 1 :(得分:0)

您没有使用变量来构建网址:

window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"

相反,请使用"关闭字符串并附加值和后续字符串:

window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "lastname=" + data['lastname'] + "email=" + data['email'] + "code=" + data['code']

此外,您似乎缺少参数分隔符(&),所以我应该是:

window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "&lastname=" + data['lastname'] + "&email=" + data['email'] + "&code=" + data['code']