drwpbrv668670 2014-04-01 11:27
浏览 47
已采纳

如何使用AJAX将Javascript数组传递给PHP文件?

I have to pass a Javascript arry to a PHP file while AJAX call.

Below is my js array:

var myArray = new Array("Saab","Volvo","BMW");

This JS code has to pass JS array to PHP file using AJAX request and will show count of array.

function ProcessAJAXRequest()
{
    $.ajax
    ({
        type: "POST",
        url: "myphpfile.php",
        data: {"id" : 1, "myJSArray" : myArray},
        success: function (data) 
        {
            alert(data);
        }
    });
}

This myphpfile.php file has to return the count of the array

<?php 
    $myPHPArray = $_POST["myJSArray"];
    echo count($myPHPArray);
 ?>

There is error in PHP file. I am getting undefined index: myPHPArray. How should acheive my required functionality?

  • 写回答

4条回答 默认 最新

  • donglong7338 2014-04-01 11:33
    关注

    Convert js array in json format by JSON.stringify

    function ProcessAJAXRequest()
    {
        $.ajax
        ({
            type: "POST",
            url: "myphpfile.php",
            data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},
            success: function (data) 
            {
                alert(data);
            }
        });
    }
    

    And In the PHP use json_decode function to get value in array

    json_decode($_POST["myJSArray"]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?