AJAX调用后可变失败值

时间:2014-04-22 17:36:55

标签: jquery ajax

// Suggested OFI Submit
$("#submit_suggested_ofi").click(function() {
    var names = $("#sofi_name").val();
    var item = $("#itemid").val();
    var item_type = $("#item_type option:selected").val();
    var notable = new Array();
    $(".notable:checked").each(function() {
        notable.push($(this).attr("id"));
    });
    notable = JSON.stringify(notable);
    var notes = $("#ofi_notes").val();
    var reading = $("#reading_notes").val();
    var aid = $("#auditor").text();
    var name_array = split(names);
    var name;
    for ( var i = 0; i < name_array.length; i++ ) {
        name = name_array[i];
        if (name && item && notes && name.trim().length > 0) {
            var query = "func=check_name&name=" + name;
            console.log("NAME: " + name);
            ajaxRequest(query, function(data) {
                console.log("NAME: " + name);
                data = data.replace(/(\r\n|\n|\r|\s)/gm, "");
                if (data == 1) {
                    if (/^\d+/.test(item)) {
                        var query = "func=submit_sofi&name=" + name + "&item=" + item + "&subtype=" + item_type + "&tags=" + notable + 
                                    "&notes=" + notes + "&reading=" + reading + "&aid=" + aid;
                        console.log(query);
                        ajaxRequest(query, function(data) {
                            successMsg(_("Suggestion Submitted"));
                            if ( i == name_array.length ) {
                                $("#sofi_name, #itemid, #ofi_notes, #reading_notes").val('');
                                $(".notable").prop('checked', false);
                            }
                        });
                    } else {
                        failureMsg(_("Item ID must be numeric"));
                    }  
                } else {   
                    failureMsg(_("Please enter a valid employee"));
                }
            });
        } else {
            failureMsg(_("Please fill out the required fields."));
        }  
    }  
});

在第一次调用ajaxRequest之后,name变量似乎丢失了它的值,如下面的控制台输出所示:

NAME: Sean Garrett 
NAME: 
func=submit_sofi&name=&item=165151&subtype=chat&tags=["Policy Violation Issue"]&notes=dfgdffg&reading=dfdfdf&aid=3042

我做错了什么?

function ajaxRequest(query, callback) {
    $.ajax({
        type: "POST",
        url: "process/process.php",
        data: query,
        success: callback,
    });
}

1 个答案:

答案 0 :(得分:0)

var name;内有function () { }。这意味着它是该范围的局部变量,并且在函数完成时将丢失,并在再次输入函数时重新重置。

您还可以$("#sofi_name, #itemid, #ofi_notes, #reading_notes").val('');清除#sofi_name字段。当函数启动时,它会使用names

var names = $("#sofi_name").val();

所以也许你正在清除#sofi_name字段,因此名字第二次变空。