简体   繁体   English

JavaScript jquery.ajax在循环后成功无法正常工作

[英]JavaScript jquery.ajax in success after loop nothing working

I need to pass some values to other function in Javascript. 我需要将一些值传递给Javascript中的其他函数。 I have got the values from another PHP file but I can not pass it to any other Javascript Function. 我已经从另一个PHP文件中获取了值,但是无法将其传递给任何其他Javascript函数。 Nothing is working in SUCCESS after FOR LOOP. FOR LOOP之后,没有任何事情可以成功进行。 Need Help? 需要帮忙?

url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php';
$.ajax({
    url: url1,
    type: "POST",
    dataType: "json",
    success: function(data)
    {
        for(var i = 0; i <= 11; i++) 
        {
            Month = data[i].Month;
            Sales = data[i].Sales;
            if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
            else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
        }
        alert ("hello"); // this alert is also not working
    }
});

That's because you are performing an asynchronous AJAX operation. 那是因为您正在执行异步 AJAX操作。 In other words, the assignments on variables Month , Sale , global_ij that you are making are only available in that particular success function's scope and NOT outside of it. 换句话说,您在变量MonthSaleglobal_ij所做的赋值在该特定success函数的范围内可用, global_ij在该范围之外

One workaround for you is to add async: false to your AJAX call which will force it out of asynchronous behavior, therefore allowing you to make the values assigned to those variables available to all the remaining block of code: 一种解决方法是在AJAX调用中添加async: false这将迫使它退出异步行为,因此使您可以将分配给这些变量的值提供给所有其余代码块:

$.ajax({
url: url1,
async: false,
type: "POST",
dataType: "json",
success: function(data)
{
    for(var i = 0; i <= 11; i++) 
    {
        Month = data[i].Month;
        Sales = data[i].Sales;
        if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
        else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
    }
}
});

jQuery's AJAX calls return promise objects which enforce methods such as .done() , .fail() , etc. jQuery的AJAX调用返回会执行诸如.done() .fail()等方法的promise对象。

On the other hand, you could also get a promise from the AJAX call (which you can pass around anywhere in your Javascript code) and when the promise gets resolved invoke it's .done() handler. 另一方面,您还可以从AJAX调用中获得承诺 (可以在Javascript代码中的任何地方传递该承诺),并且当承诺被解析时调用它的.done()处理函数。

var promise = $.ajax({/* settings */});

/* --- */

// promise passed to some other block of code

promise.done(function(){
    //execute the block of code after the promise was resolved
});

Read more about this here . 在此处阅读有关此内容的更多信息

looks like your php is returning 8 elements and in your success method your loop iterates over 11 items, causing error. 看起来您的php返回8个元素,并且在您的成功方法中,循环迭代了11个项目,从而导致错误。

I separated the success function and tried it with the data you posted and replaced the 11 in the loop with data.length. 我分离了成功函数,并用您发布的数据进行了尝试,并用data.length替换了循环中的11。 take a look at the following codepen: 看一下下面的codepen:

http://codepen.io/anon/pen/OyXzGb?editors=011 http://codepen.io/anon/pen/OyXzGb?editors=011

note that I added 请注意,我添加了

var Month; var Month;

var Sales; var Sales;

to keep those temporary variables inside the scope of the function. 将这些临时变量保留在函数范围内。

You might need to check Data to see if it is a proper array, to catch errors. 您可能需要检查数据以查看它是否是正确的数组,以捕获错误。 before this line: 在此行之前:

for(var i = 0; i < data.length ; i++) for(var i = 0; i < data.length ; i ++)

final output and something to try out: 最终输出和一些尝试的方法:

var global_ij="";
function processData(data) {
    var Month;
    var Sales;
    for(var i = 0; i < data.length; i++) 
    {
        Month = data[i].Month;
        Sales = data[i].Sales;
        if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
        else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
        console.log(global_ij);
    }
    return global_ij;
}

try out this function without the ajax first: 首先尝试不使用ajax的此功能:

processData([{"Month":"1","Year":"2015","Sales":"19746.81"}, processData([{“ Month”:“ 1”,“ Year”:“ 2015”,“ Sales”:“ 19746.81”},
{"Month":"2","Year":"2015","Sales":"17902.26"},{"Month":"3","Year":"2015","Sales":"19223.84"},{"Month":"4","Year":"2015","Sales":"18840.88"},{"Month":"5","Year":"2015","Sales":"19889.97"},{"Month":"6","Year":"2015","Sales":"18509.85"},{"Month":"7","Year":"2015","Sales":"1886.81"},{"Month":"8","Year":"2015","Sales":"1740.34"}]); {“ Month”:“ 2”,“ Year”:“ 2015”,“ Sales”:“ 17902.26”},{“ Month”:“ 3”,“ Year”:“ 2015”,“ Sales”:“ 19223.84” },{“ Month”:“ 4”,“ Year”:“ 2015”,“ Sales”:“ 18840.88”},{“ Month”:“ 5”,“ Year”:“ 2015”,“ Sales”:“ 19889.97“},{” Month“:” 6“,” Year“:” 2015“,” Sales“:” 18509.85“},{” Month“:” 7“,” Year“:” 2015“,” Sales“ :“ 1886.81”},{“ Month”:“ 8”,“ Year”:“ 2015”,“ Sales”:“ 1740.34”}]));

you might want to use .done() 您可能想使用.done()

Modify your code to declare the gloabla_ij variable outside the loop. 修改您的代码以在循环外声明gloabla_ij变量。 somehting like below.. 像下面这样

var global_ij='0';
url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php';
$.ajax({
    url: url1,
    type: "POST",
    dataType: "json",
    success: function(data)
    {
        for(var i = 0; i <= 11; i++) 
        {
            Month = data[i].Month;
            Sales = data[i].Sales;
            if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
            else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
        }
    }
});

If you declare the var at the top of the file, it can be used by any function within the file: 如果在文件顶部声明var,则文件中的任何函数都可以使用它:

var global_ij; // declare variable in global scope of module/file

$.ajax({
    url: 'http://localhost:81/Dashboard/admin/inc/dashboard.php',
    type: "POST",
    dataType: "json",
    success: function(data) {

        var i, month, sales, len = data.length;

        for(i=0; i<=len; i++) {

            month = data[i].Month;
            sales = data[i].Sales;

            if (i===0) global_ij = "[" + month + "," + sales + "]";
            else global_ij = global_ij + "," + "[" + month + "," + sales + "]";
        }

        doSomething(); // can now call function after loop finished
    }
});

func doSomething() {
    // global_ij is now populated
}

The response from the PHP file is: PHP文件的响应为:

[
    {"Month":"1","Year":"2015","Sales":"19746.81"},  // 1
    {"Month":"2","Year":"2015","Sale‌​s":"17902.26"},  // 2
    {"Month":"3","Year":"2015","Sales":"19223.84"},  // 3
    {"Month":"4","Year"‌​:"2015","Sales":"18840.88"},  // 4
    {"Month":"5","Year":"2015","Sales":"19889.97"},  // 5
    {"Mont‌​h":"6","Year":"2015","Sales":"18509.85"},  // 6
    {"Month":"7","Year":"2015","Sales":"1886‌​.81"},   // 7
    {"Month":"8","Year":"2015","Sales":"1740.34"}    // 8
]

Yet you are looping 然而你在循环

for(var i = 0; i <= 11; i++) 

So when i >= 8 , data[i].Month will throw an "data[i] is undefined" error. 因此,当i >= 8data[i].Month将引发“ data [i]未定义”错误。

Simply use the .length property instead: 只需使用.length属性即可:

for(var i = 0; i < data.length; i++) 

Example Fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM