简体   繁体   English

如何使用Ajax和Jquery将javascript数组传递给php数组

[英]How to pass javascript array to php array using Ajax and Jquery

I'm trying to pass a Javascript array into a PHP array through jQuery and Ajax. 我正在尝试通过jQuery和Ajax将Javascript数组传递到PHP数组。 The PHP script should then write the array into a MySQL database, with each individual entry in the array being assigned to a separate column in the database. 然后,PHP脚本应将数组写入MySQL数据库,并将数组中的每个单独条目分配给数据库中的单独列。 This is the code I'm currently using (which doesn't work!) 这是我当前正在使用的代码(不起作用!)

Javascript: Javascript:

The array is contained in a variable called 'modules' 该数组包含在名为“模块”的变量中

   $.ajax({
        url: "newaccount.php",
        type: "POST",
        data: {modules: modules},
        success: function(){
         modules.length = 0;
         $("#result").html("Success");
         },
     });

PHP: PHP:

 $modules = $_POST['modules'];

 if(mysql_query ("INSERT INTO level3 (mod1, mod2, mod3, mod4) VALUES ('$modules')")) {
  echo "Successfully inserted";
 }
 else {
  echo "Insertion Failed";
 }

This is a simplified version - usually there are other values inserted into the database alongside this which are not contained in arrays. 这是一个简化的版本-通常将其他值插入数据库中,这些值不包含在数组中。 These seem to be working fine, but when I try to insert the array values nothing goes in - the database columns remain as 'null' 这些似乎工作正常,但是当我尝试插入数组值时什么也没进-数据库列仍然为'null'

Please help! 请帮忙! I've been banging my head against this brick wall all day! 我整天都在撞砖墙。

What you are looking for is called serialization technique. 您正在寻找的被称为序列化技术。 You should serialize the javascript variable and send it to php, where it can deserialize it again. 您应该序列化javascript变量并将其发送到php,在此它可以再次反序列化它。 You can refer to following posts which will help you to find out the solution. 您可以参考以下文章,以帮助您找到解决方案。

Serializing to JSON in jQuery 在jQuery中序列化为JSON

serialize javascript array 序列化javascript数组

http://api.jquery.com/serializeArray/ http://api.jquery.com/serializeArray/

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

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