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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里