简体   繁体   English

如何从ajax在php中取回数组

[英]How to get array back in php from ajax

I have an array like this in php :我在 php 中有一个这样的数组:

Array
(
    [week] => 15
    [showing] => present
    [ignore_team_id] => Array
        (
            [0] => 362
            [1] => 343
            [2] => 352
            [3] => 331
        )

    [event_pasted_team_id] => Array
        (
        )

    [old_data] => old_data
)

I want to get this array back in php from ajax.我想从 ajax 将这个数组恢复到 php 中。 This is what I did so far.这是我到目前为止所做的。

I just encode the array into json and saved it in hidden field using json_encode();我只是将数组编码为 json 并使用json_encode();将其保存在隐藏字段中json_encode();

<input id='myArray' type='hidden' name="myArray" value='<?php echo json_encode($myArray);?>' /> 

In javascript:在 JavaScript 中:

function ajaxloadPlage(outputId,dataTransfer){
            myArrayVal = jQuery('#myArray').val();
            strify = JSON.stringify(myArrayVal);
            jQuery.get( myapp.ajaxurl+'?'+dataTransfer,{action:'getPlayerRaterData','getArr':strify}, function( data ) {
            //business login goes here
                });
    }

Back in PHP:回到 PHP:

if($_GET['getArr']){
    $getArr = $_GET['getArr'];
    echo '<pre>';print_r($getArr);
}

Its print like this:它的打印是这样的:

\"{\\\"week\\\":15,\\\"showing\\\":\\\"present\\\",\\\"ignore_team_id\\\":[362,343,352,331],\\\"event_pasted_team_id\\\":[],\\\"old_data\\\":\\\"old_data\\\"}\"

How can I get the valid array back?如何取回有效数组?

You have encoded the array in json during sending but not decoded in back php.您在发送期间已将数组编码为 json,但未在后台 php 中解码。 try like this..试试这样..

PHP: PHP:

<?php
if($_GET['getArr']){
    $getArr = $_GET['getArr'];
    echo '<pre>';print_r(json_decode($getArr));
}
?>

Hope this will solve ur issue.希望这能解决你的问题。

myArrayVal is already a JSON string, you don't need to call JSON.stringify . myArrayVal已经是一个 JSON 字符串,你不需要调用JSON.stringify You should call JSON.parse() to convert it to an object.您应该调用JSON.parse()将其转换为对象。 $.get() will then URL-encode the object, and PHP will decode this when it sets $_GET['getArr'] . $.get()然后会对对象进行 URL 编码,PHP 会在设置$_GET['getArr']时对其进行解码。

function ajaxloadPlage(outputId,dataTransfer){
    myArrayVal = jQuery('#myArray').val();
    myArray = JSON.parse(myArrayVal);
    jQuery.get( myapp.ajaxurl+'?'+dataTransfer,{action:'getPlayerRaterData','getArr':myArray}, function( data ) {
        //business login goes here
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM