执行函数时为什么有两个不同的值?

时间:2015-05-05 07:35:12

标签: javascript jquery

我不知道为什么,但是当我只运行(kpis1)时,我得到结果(100)但是当我运行(kpis2)时我才得到结果(97)。

在运行它们时,结果变为kpis1 = 100但kpis2 = 70?

为什么函数给出单个参数的正确结果,但是当我放入两个参数时结果错误?

<script src="../../scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/jscript">
var isProd = true;
var MAX_PROCESS_PER_ELEMENT = 30;
var NUMBER_OF_ELEMENT = 11;
var elements = new Array(NUMBER_OF_ELEMENT);
var totalRolled = 0;
var totalDeveloped = 0;
var totalImplement = 0;
var totalCount = 0;
var totalOwners = 0;
var totalChampions = 0;
var totalAssessed = 0;
var totalItemsClosed = 0;
var totalItemsPending = 0;

var chartIm;

var colors = ["31116e", "5e646f", "009861", "005b8c", "874614", "cc202b", "b85c27", "eb8030", "005a5a", "5ca6de", "842790"];
var bgColor = "fcfdfd"; //"feeebd";
var chartAlpha = 60;

var COLUMN_NO = "ows_No";
var COLUMN_TITLE = "ows_Title";
var COLUMN_ID = "ows_ID";
var COLUMN_LINK = "ows_Link";
var COLUMN_ELEMENT = "ows_Element";
var COLUMN_OWNER = "ows_Owner";
var COLUMN_PROCESS_WEIGHT = "ows_Weight_x0025_";
var COLUMN_IMPLM_SCORE = "ows_Aduit_x0020_Score";
var COLUMN_IS_DEVELOPED = "ows_Developed";
var COLUMN_IS_ROLLED_OUT = "ows_Rolled_x0020_Out";
var COLUMN_IS_ASSESSED = "ows_Assessed";
var COLUMN_CYCLE = "ows_Assessment_x0020_Cycle";
var COLUMN_ACTION_ITEMS = "ows_Identified_x0020_GAP";
var COLUMN_LPCR = "ows_LPCR_x0020_GAPs";
var COLUMN_OTHER_GAPS = "ows_Other_x0020_GAPs";
var COLUMN_ACTION_COUNT = "ows__x0023__x0020_GAPs";
var COLUMN_ACTION_CLOSED = "ows_ClosedGaps";
var COLUMN_ACTION_PENDING = "ows_Pending_x0020_GAPs";
var COLUMN_CHAMPION = "ows_Champion";
var COLUMN_RESPONS_PERSONS = "ows_Res";
var COLUMN_RESPONS_PERSONS = "ows_Res";
var KPI_MATRIX = new Array();
var plannedEventTD = 0;
var doneEventTD = 0;
var alertMessage;

function loadSmsXmlData(sSmsXml2) {

        var sSmsXml = "https://sharepoint.com/orgs/_vti_bin/owssvr.dll?";
        sSmsXml += "Cmd=Display&XMLDATA=TRUE&Query=*?&List="+sSmsXml2;
        $.ajax({ url: (isProd ? sSmsXml : "sms.xml"),
            type: "POST", dataType: "xml",async: false,
            data: "", cache: false ,
            contentType: "text/xml; charset=\"utf-8\"",cache:false
            ,complete: processSmsResult
            ,error: function(xml,status,msg) {alert("Error in Loading the SMS Process Data \n error code:" + msg)} 
    });

 var out = [totalImplement,"Total Implement"];
alert(out);
return out;

function processSmsResult(xData, status) {

    $(xData.responseXML).children(1).children(1).children().each(function () {
        var currentElement;
        if (!isNaN($(this).attr(COLUMN_NO))) {

            var elementNo = parseInt($(this).attr(COLUMN_NO), 10);

            if (elements[elementNo - 1] == undefined) {
                var currentElement = new Element();
                currentElement.no = elementNo;
                currentElement.champion = $(this).attr(COLUMN_CHAMPION);
                currentElement.title = $(this).attr(COLUMN_ELEMENT);
                elements[elementNo - 1] = currentElement;
            }
            else { currentElement = elements[elementNo - 1] };
            var process = new Process();
            process.no = parseFloat($(this).attr(COLUMN_NO)).toFixed(2);
            if ($(this).attr(COLUMN_ACTION_CLOSED))
                process.actionClosed = parseInt($(this).attr(COLUMN_ACTION_CLOSED).substring($(this).attr(COLUMN_ACTION_CLOSED).indexOf("#") + 1), 10);
            if ($(this).attr(COLUMN_ACTION_COUNT))
                process.actionCount = parseInt($(this).attr(COLUMN_ACTION_COUNT), 10);
            if ($(this).attr(COLUMN_ACTION_ITEMS))
                process.ActionItems = $(this).attr(COLUMN_ACTION_ITEMS);
            if ($(this).attr(COLUMN_ACTION_PENDING))
                process.actionPending = parseInt($(this).attr(COLUMN_ACTION_PENDING), 10);
            if ($(this).attr(COLUMN_CYCLE))
                process.cycle = $(this).attr(COLUMN_CYCLE);
            if ($(this).attr(COLUMN_ID))
                process.id = parseInt($(this).attr(COLUMN_ID), 10);
            if ($(this).attr(COLUMN_IS_ASSESSED))
            if ($(this).attr(COLUMN_IS_ASSESSED).length > 5)
                process.isAssessed = $(this).attr(COLUMN_IS_ASSESSED).substring(0, $(this).attr(COLUMN_IS_ASSESSED).lastIndexOf(" "));
            if ($(this).attr(COLUMN_IMPLM_SCORE))
                process.implmScore = parseInt(parseFloat($(this).attr(COLUMN_IMPLM_SCORE)) * 100, 10);
            if ($(this).attr(COLUMN_IS_DEVELOPED))
                process.isDeveloped = $(this).attr(COLUMN_IS_DEVELOPED);
            if ($(this).attr(COLUMN_IS_ROLLED_OUT))
                process.isRolledout = $(this).attr(COLUMN_IS_ROLLED_OUT);
            if ($(this).attr(COLUMN_ACTION_COUNT))
                process.actionCount = parseInt($(this).attr(COLUMN_ACTION_COUNT), 10);
            if ($(this).attr(COLUMN_ACTION_ITEMS))
                process.actionItems = $(this).attr(COLUMN_ACTION_ITEMS);
            if ($(this).attr(COLUMN_LINK))
                process.link = $(this).attr(COLUMN_LINK).substring(0, $(this).attr(COLUMN_LINK).indexOf(", "));
            if ($(this).attr(COLUMN_LPCR))
                process.LPCR = $(this).attr(COLUMN_LPCR);
            if ($(this).attr(COLUMN_OTHER_GAPS))
                process.otherGaps = $(this).attr(COLUMN_OTHER_GAPS);
            if ($(this).attr(COLUMN_PROCESS_WEIGHT))
                process.processWeight = (parseInt(parseFloat($(this).attr(COLUMN_PROCESS_WEIGHT).substring($(this).attr(COLUMN_PROCESS_WEIGHT).indexOf("#") + 1) * 100), 10));
            if ($(this).attr(COLUMN_TITLE))
                process.title = $(this).attr(COLUMN_TITLE);
            if ($(this).attr(COLUMN_TITLE))
                process.owner = $(this).attr(COLUMN_OWNER).replace(/^\s+|\s+$/g, "");
            if ($(this).attr(COLUMN_RESPONS_PERSONS))
                process.responsPersons = $(this).attr(COLUMN_RESPONS_PERSONS);
            process.implmScore = process.implmScore - (3*process.actionPending);
            currentElement.processes[parseInt(process.no.toString().substring(process.no.toString().indexOf(".") + 1), 10)] = process;
            process.scoreToElement = process.processWeight * process.implmScore / 100;
            currentElement.itemsClosed += process.actionClosed;
            currentElement.itemsPending += process.actionPending;
            totalItemsClosed += process.actionClosed;
            totalItemsPending += process.actionPending;
            currentElement.processesCount++;
            currentElement.implementation += process.scoreToElement;
            currentElement.fullScore += process.processWeight;
            if (process.isAssessed.toUpperCase().length > 6)
                currentElement.assessedProcesses++;
            if (process.isDeveloped.toUpperCase().indexOf("YES") > -1)
                currentElement.developedProcesses++;
            if (process.isRolledout.toUpperCase().indexOf("YES") > -1)
                currentElement.rolledoutProcesses++;
        } 

    });                    

        $(elements).each(function () {
        totalCount += this.processesCount;
        totalRolled += this.rolledoutProcesses;
        totalDeveloped += this.developedProcesses;
        totalAssessed += this.assessedProcesses;
        this.implementation = 100 * this.implementation / this.fullScore;
        totalImplement += this.implementation;
    });
      totalImplement /= NUMBER_OF_ELEMENT;

} 

function Element() {
    this.no = 0;
    this.title = "";
    this.champion = "";
    this.processesCount = 0;
    this.rolledoutProcesses = 0;
    this.developedProcesses = 0;
    this.assessedProcesses = 0;
    this.itemsClosed = 0;
    this.itemsPending = 0;
    this.implementation = 0;
    this.fullScore = 0;
    this.processes = new Array(MAX_PROCESS_PER_ELEMENT);
}
function Process() {
    this.title = "";
    this.id = -1;
    this.no = 0;
    this.link = "#";
    this.owner = "";
    this.processWeight = 0;
    this.scoreToElement = 0; 
    this.implmScore = 0;
    this.isDeveloped = "";
    this.isRolledout = "";
    this.isAssessed = "";
    this.cycle = "";
    this.ActionItems = "N/A";
    this.LPCR = "";
    this.otherGaps = "";
    this.actionCount = 0;
    this.actionClosed = 0;
    this.actionPending = 0;
    this.responsPersons = "(set)";
}
}

 kpis1 =  loadSmsXmlData("%7B474EAAB5%2D25F5%2D4669%2DB677%2DB85587EA40CA%7D");
 alert ("kpis1: "+ kpis1[0]);
 kpis2 =  loadSmsXmlData("%7B0EE4A087%2DDAF4%2D49F5%2DB4DF%2D413AF23B6C7C%7D");
 alert ("kpis2: "+ kpis2[0]);

这是我的jsfiddle https://jsfiddle.net/gs8sxean/2/

2 个答案:

答案 0 :(得分:0)

这是因为在您的processSmsResult函数中,您正在修改全局变量totalImplement,因此在后续调用同一函数时,将具有该变量的不同值。这就是你获得两种不同产出的原因。

另一件需要注意的事情是:

 var out = [totalImplement,"Total Implement"];
alert(out);
return out;

此片段最后应位于processSmsResult功能内。因为您在ajax函数的成功回调中修改了响应数据,该函数本质上是异步的。

答案 1 :(得分:0)

您的代码中有许多问题需要解决:

  • 一旦缩进,很明显你的功能实际上是嵌套的,但它们不能那样工作。
  • 你必须绝对摆脱async: false,因为这会导致更多的问题而不是它解决的问题!然后,您将尝试在启动它之后立即尝试使用来自异步操作的返回数据,而不是等待结果。这就像&#34;订购比萨饼然后在交付之前尝试吃它&#34; :)
  • 您需要对函数使用回调,或使用jQuery promise。回调更容易理解,但承诺是更清洁的选择。
  • 您期望从您的函数返回结果,但您的函数不会返回任何内容。
  • 您不在处理函数中使用status,因此请勿将其传递。

假设processSmsResult也不是异步操作,你可以这样设置:

回拨版本:

function loadSmsXmlData(sSmsXml2, callback) {

    var sSmsXml = "https://sharepoint.com/orgs/_vti_bin/owssvr.dll?";
    sSmsXml += "Cmd=Display&XMLDATA=TRUE&Query=*?&List="+sSmsXml2;
    $.ajax({ url: (isProd ? sSmsXml : "sms.xml"),
        type: "POST", dataType: "xml",
        data: "", cache: false ,
        contentType: "text/xml; charset=\"utf-8\"",cache:false
        ,complete: callback
        ,error: function(xml,status,msg) {alert("Error in Loading the SMS Process Data \n error code:" + msg)} 
});

并像这样使用:

loadSmsXmlData("%7B474EAAB5%2D25F5%2D4669%2DB677%2DB85587EA40CA%7D", function(data, status){
            var kpis = processSmsResult(data);
            // Now you can alert the result of this operation
        });

承诺版本:

// Simple return the $.ajaz promise
function loadSmsXmlData(sSmsXml2, callback) {

    var sSmsXml = "https://sharepoint.com/orgs/_vti_bin/owssvr.dll?";
    sSmsXml += "Cmd=Display&XMLDATA=TRUE&Query=*?&List="+sSmsXml2;
    return $.ajax({ url: (isProd ? sSmsXml : "sms.xml"),
        type: "POST", dataType: "xml",
        data: "", cache: false ,
        contentType: "text/xml; charset=\"utf-8\"",cache:false
});

并使用如下:

loadSmsXmlData("%7B474EAAB5%2D25F5%2D4669%2DB677%2DB85587EA40CA%7D").done(function (function (data) {
        kpis = processSmsResult(data);
        // Now you can alert the result of this operation
}).fail(function (hdr, textStatus) {
        alert("Error in Loading the SMS Process Data \n error code:" + textStatus)
});

最后一个问题是由于尝试将函数的结果分配给变量,例如kpis1 = loadSmsXmlData,但该函数不返回任何内容,因此也不起作用。

在异步世界中,您希望等待两者成功,无论是顺序还是并行。所以改变用法是这样的:

var load1 = loadSmsXmlData("%7B474EAAB5%2D25F5%2D4669%2DB677%2DB85587EA40CA%7D");
var load2 = loadSmsXmlData("%7B0EE4A087%2DDAF4%2D49F5%2DB4DF%2D413AF23B6C7C%7D");
$.when(load1, load2).done(function(data1, data2){
    // both complete, process the results
    var kpis1 = processSmsResult(data1);
    var kpis2 = processSmsResult(data2);
}).fail(function(hdr, textStatus){
    alert("Error in Loading the SMS Process Data \n error code:" + textStatus)
});

其他问题:

您需要自己的功能来执行自包含操作。要避免的一件事是使用任何全局变量,因为它会引入依赖关系。

例如,您可以更改processSmsResult函数以实际返回结果。