简体   繁体   English

如何使用 JSON 在 AJAX 中发送数组

[英]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.我对 JS 和 AJAX 相当陌生,由于某种原因,我无法通过 AJAX 发送动态生成和读取的数据。 How do I properly send an array via AJAX to PHP script?如何通过 AJAX 将数组正确发送到 PHP 脚本?

I have tried following the instructions but I can not get the AJAX to send the data.我已尝试按照说明操作,但无法让 AJAX 发送数据。 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.但它似乎源自 JS 库而不是我的代码(尽管代码很可能是它的原因!)而且我不知道如何处理它。

    //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二、使用jquery序列化

$.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));你可以使用 //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"

});

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

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