简体   繁体   中英

How to send array in AJAX using JSON

I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?

I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:

Uncaught TypeError: Illegal invocation

but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.

    //first thing I tried
    var i = 1, j = 0, cu = [], cu2 = [];
     while (i <= tilit ) {
        cu[j] = document.getElementById("til_nro_"+i);
        console.log(cu[j].value);

        i++;
    }
    var dynamic_account_value = JSON.stringify(cu);


 jQuery.ajax({
        type: "POST",
         url: 'http:mysite.php',
        dataType: 'json', 
        data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
            }
        });



    //2nd thing I tried
    var i = 1, j = 0, cu = [], cu2 = [];
     while (i <= tilit ) {

        cu[j] = document.getElementById("til_nro_"+i);
        cu2.push(JSON.parse(cu[j].value));

        i++;
    }
    var tilinrot_lisa = JSON.stringify(cu2);


     jQuery.ajax({
        type: "POST",
         url: 'http:mysite.php',
        dataType: 'json', 
        data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
            }
        });

First, give them something that makes selection easier, like a common class. Second, use jquery serialize

$.ajax({
  url : "foo",
  data : $(".bar").serialize(),
  success : function(response) {}
})

Try this code snippet, Try to send just one variable then go for another & use content type. u can use //console.log(JSON.stringify(cu)); to view what's inside.

jQuery.ajax({
   type: 'post',
   dataType: 'json',
   data: {your_var:JSON.stringify(cu)},
   contentType: "application/json"

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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