How to pass Javascript array to PHP file using AJAX?

狂风中的少年 提交于 2021-01-28 05:41:40

问题


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?


回答1:


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"]);



回答2:


Use JSON.stringify to converts a value to JSON and send it to server.

data: JSON.stringify({"id" : 1, "myJSArray" : myArray})



回答3:


You could use JSON.stringify(array) to encode your array in JavaScript, and then use

$array=json_decode($_POST['jsondata']);

in your PHP script to retrieve it.please check this link

Pass Javascript Array -> PHP




回答4:


What seems to me is that your array is not available in the function scope:

function ProcessAJAXRequest(){
   var myArray = new Array("Saab","Volvo","BMW"); // this has to be in fn scope
   $.ajax({
      type: "POST",
      url: "myphpfile.php",
      data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},  // do the stringify before posting
      success: function (data){
         alert(data);
      }
   });
}


来源:https://stackoverflow.com/questions/22784515/how-to-pass-javascript-array-to-php-file-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!