admin管理员组

文章数量:1279243

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:

I never used the for loop in JS, but seems familiar anyway.

The way the loop is made, obviously wont work:

for (i=0;i<required.length;i++) {
        var required[i] = $('#'+required[i]).attr('value');

This will create the variables i want, how to use them?

HOPEFULLY, you guys can help me!!! Thank you very much!

required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];              


function ajaxrequest() {
    for (i = 0; i < required.length; i++) {
        var required[i] = $('#' + required[i]).attr('value');
        var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
    }
    $.ajax({
        type: "POST",
        url: "ajaxload/o.php",
        data: dataString,
        success: function() {
            $(".agendarleft").html("SUCESS");
        }
    });

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:

I never used the for loop in JS, but seems familiar anyway.

The way the loop is made, obviously wont work:

for (i=0;i<required.length;i++) {
        var required[i] = $('#'+required[i]).attr('value');

This will create the variables i want, how to use them?

HOPEFULLY, you guys can help me!!! Thank you very much!

required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];              


function ajaxrequest() {
    for (i = 0; i < required.length; i++) {
        var required[i] = $('#' + required[i]).attr('value');
        var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
    }
    $.ajax({
        type: "POST",
        url: "ajaxload/o.php",
        data: dataString,
        success: function() {
            $(".agendarleft").html("SUCESS");
        }
    });
Share Improve this question edited Jul 11, 2012 at 15:42 Esailija 140k23 gold badges279 silver badges328 bronze badges asked Jul 11, 2012 at 15:41 SouzaSouza 1,1435 gold badges19 silver badges47 bronze badges 6
  • how can i make a "for" loop, using an array? – Souza Commented Jul 11, 2012 at 15:47
  • Yeah it's not very clear. To have a stab at deciphering this; are you wondering how to get the values you're putting in your required array to be passed as key/value pairs in your POST request the way they would be if you'd submitted a form? – Vala Commented Jul 11, 2012 at 15:48
  • @Souza you've already made a for loop, as far as I can tell it should loop over every value in required and get values from fields with those IDs. You're not making yourself very well understood. – Vala Commented Jul 11, 2012 at 15:50
  • @Thor84no check out the var dataString, you think the output will be correct? – Souza Commented Jul 11, 2012 at 15:57
  • @Souza I don't know what you'd expect, so I can't tell you. Also I haven't got anywhere to execute this code right now, but I'd say you're not doing what you intend. It looks like you intend dataString to contain 'nome=<user-input>&sobrenome=<user-input>', but for that you should put it after the for loop, not inside. You should also define the array of values outside of the for loop and fill it inside it. Oh, and I'd store the values in a different array to the one you have the IDs in rather than overwrite it. – Vala Commented Jul 11, 2012 at 16:00
 |  Show 1 more ment

3 Answers 3

Reset to default 4

To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.

jQuery:

required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];

function ajaxrequest() {
    var params = {}; // initialize object

    //loop through input array
    for (var i=0; i < required.length; i++) {             
        // set the key/property (input element) for your object
        var ele = required[i]; 
        // add the property to the object and set the value
        params[ele] = $('#' + ele).val(); 
    }
    $.ajax({
        type: "POST",
        url: "ajaxload/o.php",
        data: params,
        success: function() {
            $(".agendarleft").html("SUCESS");
        }
    });
}

Demo: http://jsfiddle/kPR69/

What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;

var obj = {};

$('.save').each(function () {

       var key = $(this).attr('id');
       var val = $(this).val();

       if (typeof (val) == "undefined")
           val = "''"

       obj[key] = val;
}

Then send obj as the data property of your AJAX call....

There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.

I would suggest using pre-written library, a few I included below.

http://jquery.malsup./form/#validation

https://github./posabsolute/jQuery-Validation-Engine

Otherwise the follow would get you close. You may need to covert the array into a string.

var required = ['nome','sobrenome'];              

function ajaxrequest() {
  var values;
  for (i = 0; i < required.length; i++) {
    var values[i] = $('#' + required[i]).attr('value');
  }
  $.ajax({
    type: "POST",
    url: "ajaxload/o.php",
    data: values,
    success: function() {
        $(".agendarleft").html("SUCESS");
    }
});

}

本文标签: javascriptUse a FOR loop within an AJAX callStack Overflow