2014-09-10 132 views
1

我相当新手使用JS和AJAX,由于某些原因,我无法通过AJAX发送我的动态生成和读取数据,并希望有人能帮助我。如何正确地通过AJAX发送数组到PHP脚本?我试着按照说明操作,但是我无法让AJAX发送数据。第一次尝试是一个完整的破坏,第二次得到错误:Uncaught TypeError:非法调用,但它似乎来自JS库而不是我的代码(尽管代码很可能是它的原因!),我不知道该怎么办。json如何发送数组在AJAX

//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 
      } 
     }); 

在此先感谢大家。

+1

[可能的复制(http://stackoverflow.com/questions/2013728/passing-javascript-array-to-php-through-jquery-ajax) – Jayachandran 2014-09-10 08:20:28

+1

看看'$ .PARAM() 'http://api.jquery.com/jquery.param/ – T00rk 2014-09-10 08:20:48

+1

我认为你正在尝试对DOM节点进行字符串化,试试这个,而不是'cu [j] = document.getElementById(“til_nro _”+ i).value;'。 – dfsq 2014-09-10 08:21:11

回答

1

首先,给他们一些让选择更容易的东西,就像普通的班级一样。其次,使用jQuery序列化

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

无法获得序列化或字符串化工作,因此尝试将“未触及”的cu当作dynaamic:cu,但是当我读取发送数据并接收它时,我只获取最后一个值。 – user1054844 2014-09-10 09:26:52

+0

我不太知道如何序列化它,因为我在动态内容上生成了div id ... – user1054844 2014-09-10 09:28:06

0

试试这个代码片段,尝试发送只有一个变量,然后去另一个&使用的内容类型。 你可以使用//console.log(JSON.stringify(cu));查看里面的内容。

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

});