将多维数组从JQuery AJAX发送到PHP

时间:2022-10-08 18:36:51

i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this

我想从JQuery AJAX向PHP发送一个多维数组,但它正在这样的PHP中接收

Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)

i must be doing some stupid mistake. here is the code. it gets records from a table and send to PHP

我一定是在做一些愚蠢的错误。这是代码。它从表中获取记录并发送给PHP

$(document).on('click','.savenow',function(){
    recordid = $(this).data('id');

    locations = [];

    $('.selectrec').each(function () {
        parent = $(this).parent().parent();

        name    = parent.find('td').eq(5);
        address = parent.find('td').eq(6);
        lat     = parent.find('td').eq(1);
        lng     = parent.find('td').eq(2);

        row = [name,address,lat,lng];

        locations.push(row);
    });

    locations = locations.toString();
    $.ajax({
        type: "POST",
        url:'/record/saveSearchedLocations',
        data: { recordid: recordid,locations:locations },
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error:function(data){
          alert("something went wrong, please try again.");
        }
    });

});

and this is the PHP function where i am receiving the data:

这是我接收数据的PHP函数:

function saveSearchedLocations(){
    print_r($_POST);
}

4 个解决方案

#1


4  

Use JSON.stringify() instead of toString() like so:

使用JSON.stringify()而不是toString(),如下所示:

Change your AJAX call to this:

将您的AJAX调用更改为:

$(document).on('click','.savenow',function(){
    recordid = $(this).data('id');

    locations = [];

    $('.selectrec').each(function () {
        parent = $(this).parent().parent();

        name    = parent.find('td').eq(5);
        address = parent.find('td').eq(6);
        lat     = parent.find('td').eq(1);
        lng     = parent.find('td').eq(2);

        row = [name,address,lat,lng];

        locations.push(row);
    });

    ajaxData = { recordid : recordid,locations : locations }
    $.ajax({
        type: "POST",
        url:'/record/saveSearchedLocations',
        data: JSON.stringify(ajaxData),
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error:function(data){
          alert("something went wrong, please try again.");
        }
    });

});

JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.

JSON.stringify()将您的数组转换为实际的json字符串,而不是Array.prototype.toString(),它使用逗号作为分隔符连接您的数组(一个级别)。

#2


1  

Take this answer as a reference:

以此答案为参考:

I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.

我认为您需要使用JSON.stringify(selectedData)才能在服务器端使用它。

jQuery:

var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);

$.post('serive.php', { DTO: JSON.stringify(selectedData) }, 
function(data){ /* handle response,  */ });

service.php:

header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');

$foo = json_decode($_POST['DTO']);


$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data

echo json_encode($arr);

This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"

这应该让你开始。在你的ajax响应中,alert(data.a)会警告“1”

#3


0  

sendAjax = function() {
      var data = {

             foo: 123,
             bar: 456,
             rows: [{
                 column1: 'hello',
                 column2: 'hola',
                 column3: 'bonjour',
             }, {
                 column1: 'goodbye',
                 column2: 'hasta luego',
                 column3: 'au revoir',
             }, ],
             test1: {
                 test2: {
                     test3: 'baz'
                 }
             }
         };

         $.ajax({
             type: 'post',
             cache: false,
             url: './ajax/',
             data: data
         });
     }

When the button is clicked, the following structured data shows up in PHP's $_POST variable:

单击该按钮时,以下结构化数据显示在PHP的$ _POST变量中:

Array
    (
        [foo] => 123[bar] => 456[rows] => Array(
            [0] => Array(
                [column1] => hello[column2] => hola[column3] => bonjour
            )

            [1] => Array(
                [column1] => goodbye[column2] => hasta luego[column3] => au revoir
            )

        )

        [test1] => Array(
            [test2] => Array(
                [test3] => baz
            )

        )

    )

This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object

这只适用于jQuery 1.4.0+。否则jQuery只是在键“row”的嵌套数组上调用.toString(),在键“test1”上调用嵌套对象,然后使用无用的值“[object object]将它们传递给PHP

here is the link u can check here https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/

这里是你可以在这里查看的链接https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/

#4


0  

Put your data in a form and send form data with serializeArray()

将数据放入表单并使用serializeArray()发送表单数据

#1


4  

Use JSON.stringify() instead of toString() like so:

使用JSON.stringify()而不是toString(),如下所示:

Change your AJAX call to this:

将您的AJAX调用更改为:

$(document).on('click','.savenow',function(){
    recordid = $(this).data('id');

    locations = [];

    $('.selectrec').each(function () {
        parent = $(this).parent().parent();

        name    = parent.find('td').eq(5);
        address = parent.find('td').eq(6);
        lat     = parent.find('td').eq(1);
        lng     = parent.find('td').eq(2);

        row = [name,address,lat,lng];

        locations.push(row);
    });

    ajaxData = { recordid : recordid,locations : locations }
    $.ajax({
        type: "POST",
        url:'/record/saveSearchedLocations',
        data: JSON.stringify(ajaxData),
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error:function(data){
          alert("something went wrong, please try again.");
        }
    });

});

JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.

JSON.stringify()将您的数组转换为实际的json字符串,而不是Array.prototype.toString(),它使用逗号作为分隔符连接您的数组(一个级别)。

#2


1  

Take this answer as a reference:

以此答案为参考:

I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.

我认为您需要使用JSON.stringify(selectedData)才能在服务器端使用它。

jQuery:

var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);

$.post('serive.php', { DTO: JSON.stringify(selectedData) }, 
function(data){ /* handle response,  */ });

service.php:

header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');

$foo = json_decode($_POST['DTO']);


$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data

echo json_encode($arr);

This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"

这应该让你开始。在你的ajax响应中,alert(data.a)会警告“1”

#3


0  

sendAjax = function() {
      var data = {

             foo: 123,
             bar: 456,
             rows: [{
                 column1: 'hello',
                 column2: 'hola',
                 column3: 'bonjour',
             }, {
                 column1: 'goodbye',
                 column2: 'hasta luego',
                 column3: 'au revoir',
             }, ],
             test1: {
                 test2: {
                     test3: 'baz'
                 }
             }
         };

         $.ajax({
             type: 'post',
             cache: false,
             url: './ajax/',
             data: data
         });
     }

When the button is clicked, the following structured data shows up in PHP's $_POST variable:

单击该按钮时,以下结构化数据显示在PHP的$ _POST变量中:

Array
    (
        [foo] => 123[bar] => 456[rows] => Array(
            [0] => Array(
                [column1] => hello[column2] => hola[column3] => bonjour
            )

            [1] => Array(
                [column1] => goodbye[column2] => hasta luego[column3] => au revoir
            )

        )

        [test1] => Array(
            [test2] => Array(
                [test3] => baz
            )

        )

    )

This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object

这只适用于jQuery 1.4.0+。否则jQuery只是在键“row”的嵌套数组上调用.toString(),在键“test1”上调用嵌套对象,然后使用无用的值“[object object]将它们传递给PHP

here is the link u can check here https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/

这里是你可以在这里查看的链接https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/

#4


0  

Put your data in a form and send form data with serializeArray()

将数据放入表单并使用serializeArray()发送表单数据