2017-03-15 106 views
-1

我有一个PHP文件像这样的列表:传递一个JavaScript数组到PHP

<ul id="alist"> 
    <li>Item1</li> 
    <li>Item2</li> 
    <li>Item3</li> 
</ul> 

使用jQuery我已经能够抓住这个列表:

var array = []; 
$("#alist li").each(function() { 
    array.push($(this).text()) 
}); 

阅读几个职位后关于使用json,ajax,这是我尝试过没有成功的。在我的js文件:

$.ajax({ 
    type: "POST", 
    url: "checklist.php", 
    data: { kvcArray : array}, 
    success: function() { 
     alert("Success"); 
    } 
}); 

在我的PHP文件:

<?php 
    $myArray = $_POST['kvcArray']; 
    var_dump($myArray) 
?> 

我得到 “空”,赞赏任何帮助的结果。

+0

您是否尝试过呼应发布的数据? – NewToJS

+0

可能重复的[在jQuery中序列化为JSON](http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery) – Rikin

+0

回声仍然返回空 – Bryant

回答

0

一个直接的方式做到这一点是你的追加数组的值到一个隐藏输入字段的形式。

  1. 使用jQuery抢列表值和推到一个数组
  2. 数组转换为字符串,准备提交表单
  3. 添加一个隐藏输入到表格的ID和一个空值属性
  4. 将您的字符串追加到此输入字段。
  5. 在提交您的文章后,在PHP上,您将能够将您的数组看作一个字符串。
  6. 转换回php阵列和presto!

欢迎您

-1

我发现通过查询字符串中传递值的一个很好的例子,在http://webcheatsheet.com/php/passing_javascript_variables_php.php

<script type="text/javascript"> 

width = screen.width; 
height = screen.height; 

if (width > 0 && height >0) { 
    window.location.href = "http://localhost/main.php?width=" + width + "&height=" + height; 
} else 
    exit(); 

</script> 

PHP

<?php 
echo "<h1>Screen Resolution:</h1>"; 
echo "Width : ".$_GET['width']."<br>"; 
echo "Height : ".$_GET['height']."<br>"; 
?> 
+0

此外,这个问题有堆栈溢出,包括这一个Javascript发布选项的几个类似的帖子http://stackoverflow.com/questions/15461786/pass-javascript-variable-to-php-via-ajax –

0

不知道如果我误解了这个问题,但能正常工作在我的电脑上(它记录您的阵列数据):

--- index.php ---

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </head> 
    <body> 

    <!-- Your list --> 
    <ul id="alist"> 
     <li>Item1</li> 
     <li>Item2</li> 
     <li>Item3</li> 
    </ul> 

    <!-- Your JS --> 
    <script> 
    var array = []; 
    $("#alist li").each(function() { 
     array.push($(this).text()) 
    }); 

    $.ajax({ 
     type: "POST", 
     url: "checklist.php", 
     data: { kvcArray : array}, 
     success: function(data) { 
      console.log(data); 
     } 
    }); 
    </script> 

    </body> 
</html> 

--- checklist.php ---

<?php print_r($_POST); ?> 
+0

这返回给我“数组()“,如果我试着用var_dump它给我数组(0){}。我真的很困惑,为什么它对我来说不同于其他人...... – Bryant