在jQuery.ajax()数据属性中动态传递值

时间:2015-04-24 07:20:02

标签: javascript jquery ajax jsp

我正在进行AJAX调用以订阅用户,并希望在数据属性中动态传递值。我该怎么做?

function submitFormWithAction(value, isSubscribedPortal) {
    //value and isSubscribedPortal is passed using jsp
    checkSelection();
    brand = ${userDataBean.profileConfiguration.profileData.profileFields['AutomobileBrand']}
    if (value == 'subscribe') {
        document.browseForm.action = "subscription.wfv";
        document.browseForm.method = "POST";
    } else if (value == 'addProfile') {
        document.browseForm.action = "addProfile.wfv?isSendAlert=false";
        document.browseForm.method = "POST";
    } else if (value == 'editProfile') {
        document.browseForm.action = "saveProfile.wfv?isSendAlert=false";
        document.browseForm.method = "POST";
    }
    if (isSubscribedPortal) {
        $.ajax({
            type: "POST",
            url: "saveViewData.wfv",
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-CSRF-Token', $('meta[name="_csrf"]').attr('content'));
            },
            // viewData is a Map<String,String> in UserDataBean.java
            // brand will be set after form is submitted, so how can I dynamically pass brand
            data:"viewData[message]= Your Profile for" + brand + "has been saved",
            success: function (msg){
                document.browseForm.submit();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("some error");
            }
        });
    } else {
        alert('Subscribing to portal');
        $.when(
            $.ajax({
                type: "POST",
                url: "subscription.wfv",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="_csrf"]').attr('content'));
                },
                data: "nextView=dummy&currentVertical=portal&isSendAlert=false",
            }),
            $.ajax({
                type: "POST",
                url: "saveViewData.wfv",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="_csrf"]').attr('content'));
                },
                // data: "viewData[message]=Your Search Profile is saved",
            })
        ).then(function (msg) {
            document.browseForm.submit();
        });
    }
}

1 个答案:

答案 0 :(得分:0)

如果您手动构建data字符串,则需要调用encodeURIComponent以确保对特殊字符进行编码,例如将空格转换为+和其他特殊字符百分比代码。

data: encodeURIComponent('viewData[message]') + '=' + encodeURIComponent("Your Profile for" + brand +"has been saved"),

然而,让jQuery为你做这件事更简单,只需指定一个对象而不是一个字符串。

data: { viewdata: { message: "Your Profile for" + brand +"has been saved" } },