weixin_33720078 2012-11-20 02:07 采纳率: 0%
浏览 19

For循环内的Ajax调用

I have an exam (tomorrow) that covers html, javascript, ajax, php, mysql and apache. I have been going over previous exams and one of the q's is to write the code for a program that displays an order form, but I am stuck on is the Ajax to keep the total (prices) box updated as amounts of products are ordered.

I have it working, but only if an amount is typed in once. In my solution if someone goes and changes an amount (say from 1 to 3) then it will add the price of 3 more of that product obviously not an ideal solution. I realise that a loop needs to be added, but after many hours of trying I can't get it to work properly. I realise this exact problem won't be in the exam but I would like to get my head around it as there will be something similar.

In the actual html code the form is created dynamically, according to what is in the database. The text box is generated with the id of the product as the text box id and the name is amt[] so that these can be sent to getTotal.php to work out the cost.

Here is the javascript/ajax that is activated on the onchange of textbox:

function getAmt(txtBox){ //in solution won't need to use this text box

    var xhr = new XMLHttpRequest();
    var id = txtBox.id; //id from the textbox - in solution won't need these two
    var amt = txtBox.val; //value that has been typed into the textbox

    var total = document.getElementById("total").value; //get current total value

    xhr.onreadystate = function(){

        if(xhr.readyState==4 && xhr.status == 200)
        {
              var result = xhr.responseText;
              document.getElementById("total").value = result;//place new total in form
        }

    }
    xhr.open("GET", "getTotal.php?amt="+amt+"&id="+id+"&tot="+tot);
    xht.send(null);
}

To get what I want, which is instead of using the current total and only the current text box, is that everytime there is a change to process each text box and overwrite the total with a new total. To do this I don't have the pass the txtBox value as I need to loop through all of the id's & values from amt[]

This code does that:

var arrayAmt = document.getElementsByName("amt[]");
var id;
var amt;
for(i=0; i<arrayAmt.length; i++)
{
    id = arrayAmt[i].id;
    amt = arrayAmt[i].value;
}

I am just stumped of where to put the for loop, or what part of the ajax call goes inside the loop.

I tried many different formats yesterday, and lost lots of study time.

I would really appreciate any suggestions on how to make this work

(can't use anything else such as jQuery)

Cheers

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!