2017-03-15 104 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