简体   繁体   English

For循环在Javascript函数中无法正常工作

[英]For loop is not working properly in Javascript function

I am sending Ajax request to php page using Javascript. 我正在使用Javascript将Ajax请求发送到php页面。

My main goals is to send ajax request to PHP page and get the response which I have done that already. 我的主要目标是将ajax请求发送到PHP页面并获得我已经完成的响应。

The problem is when the Ajax send back the response the Javascript cannot send this to HTML properly. 问题是当Ajax发送回响应时,Javascript无法将其正确发送到HTML。

Look at my code so you can understand clearly. 查看我的代码,这样您可以清楚地理解。

Javascript code:

function get_rental_fee(){
        var count_model = $('#count_model').val();
        for(var i =0; i < count_model; i++){

        var hours = $('#hours').val();
        var modelid = $('#modelid_multi'+i).val();
        var get_tax = $('#get_tax_multi'+i).val();
        var get_counter = $('#get_counter_multi'+i).val();
        var myData = "hours="+hours+"&modelid="+modelid+"&get_tax="+get_tax;

    jQuery.ajax({

            type: "POST", // Post / Get method

            url: "get_rental_fee.php", //Where form data is sent on submission

            dataType:"text", // Data type, HTML, json etc.

            data:myData, //Form variables

            success:function(response){


                var result = response.split('|');

                       document.getElementById('rental_price_multi'+i).value=result[0];
                    document.getElementById('tax_multi'+i).value=result[1];


        },




            error:function (xhr, ajaxOptions, thrownError){

                //On error, we alert user

                alert(thrownError);

            }

            });

        }

    }

The problem is here: 问题在这里:

document.getElementById('rental_price_multi'+i).value=result[0];
                        document.getElementById('tax_multi'+i).value=result[1];

The loop runs 3 times and Php is sending me back the response 3 times. 循环运行了3次,Php向我发送了3次响应。 But in Javascript Theses 2 lines are only showing VALUES of 3rd Times not 1st and 2nd. 但是在Javascript中,这2行仅显示第三次的值,而不是第一和第二。 But I am receiving response of all 3 times. 但是我收到了所有3次回复。

Also when I run the code the javascript returns back an error: 另外,当我运行代码时,javascript将返回错误:

Uncaught Type Error: Cannot set Property 'value' of null

Please help me where I am doing wrong 请帮我哪里做错了

Problem is $.ajax is by default async: true, so the value of i in loop is not the desired value when it reaches success . 问题是$ .ajax默认情况下是async:true,因此, i in的值在达到success不是所需的值。 You can simply make the ajax sync: 您可以简单地使ajax同步:

$.ajax({
  async: false,
  ...
})

Edited: 编辑:

If you still want to it to be async, you need to use closures. 如果仍然希望它异步,则需要使用闭包。

for(var i =0; i < count_model; i++){
   (function(i){// closure `i`
     $.ajax({
       type: "POST",
       ...
     });
   })(i);//<-- for loop `i`
}

Your problem is that i inside the callback no longer has the value it did when you registered the callback. 您的问题是回调中的i不再具有注册回调时的值。 This is a very common problem. 这是一个非常普遍的问题。

A common solution is to "close over" the variable i so that it retains the correct value: 常见的解决方案是“封闭”变量i ,以使其保留正确的值:

success: (function(i) {
    return function(response) {
        var result = response.split('|');
        document.getElementById('rental_price_multi'+i).value=result[0];
        document.getElementById('tax_multi'+i).value=result[1];
    })(i)

The outer function is passed i as a parameter, at which point its value in the inner callback function becomes fixed. 外部函数作为参数传递给i ,这时内部回调函数中的值固定。

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

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