将JSON数组传递给JS,然后传递给PHP

gpfsuwkq  于 11个月前  发布在  PHP
关注(0)|答案(2)|浏览(107)

我有一个这样的JSON文件。

{
    "name" : [
        "Alsa", "Alice", "Alas", "Alpha", "Beta", "Bervis", "Bankai", "Celcia", "Celsa", "Ceasar", 
        "Domino", "Dorito", "David", "Eurius", "Easter", "Ethium", "Fourin", "Flora", "Fifa", "Genius"
    ]
}

我会像这样执行jQuery AJAX 调用。

function method1(){
                $.ajax({
                url: "name_suggestion.json",
                type: "GET",
                dataType : "JSON",
                success : function(data){
                    for(i in data.name){
                        name_array.push(data.name[i]);
                    }
                }
            });
            }
            function method2(){
                $.post('search_name.php', {
                      names: JSON.stringify(name_array)
                    }, function(data, status){
                        console.log(data);
                    }
                );
            }
            $.when(method1()).then(method2);

在PHP文件中,

<?php
$nameData = json_decode($_POST['names']);
print_r($nameData[1]);
?>

当函数被调用时,它显示一个错误,说数组键未定义。
如果我传递一个用JavaScript编写的普通数组,它不会显示错误,但这不是我想要的:)我只是进入 AJAX ,所以如果有任何错误,我很想知道!
编辑:这是最终的代码,它的作品(感谢您的回答)

var name_array = [];
            function method1() {
                $.ajax({
                    url: "name_suggestion.json",
                    type: "GET",
                    dataType: "JSON",
                    success: function(data) {
                        name_array = data.name;
                        method2(name_array); 
                    }
                });
            }

            function method2(name_array) {
                $.get('search_name.php', {
                    names: JSON.stringify(name_array)
                }, function(data, status) {
                    console.log(data);
                });
            }
            method1();
bxpogfeg

bxpogfeg1#

var name_array = [];
function method1() {
    var name_array = [];

    $.ajax({
        url: "name_suggestion.json",
        type: "GET",
        dataType: "JSON",
        success: function(data) {
            for (var i in data.name) {
                name_array.push(data.name[i]);
            }

            method2(name_array); 
        }
    });
}

function method2(name_array) {
    $.post('search_name.php', {
        names: JSON.stringify(name_array)
    }, function(data, status) {
        console.log(data);
    });
}

method1();

在PHP代码中,您尝试使用print_r($nameData[1])访问$nameData的第二个元素。然而,json_decode将默认的第二个参数设置为false,返回一个对象,而不是一个数组。要访问这些元素,您应该使用箭头(->)操作符而不是方括号。

<?php
$jsonData = file_get_contents('php://input');
$nameData = json_decode($jsonData);

print_r($nameData->name[1]);
?>

希望它工作的队友!

alen0pnh

alen0pnh2#

接受@布拉德的建议--Fetch API提供了一种易于使用、功能强大且可靠的 AJAX 请求的方法。使用Fetch的“All-in-One”示例解决方案

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['names'] ) ){

        # In the Fetch call we set a FormData parameter called "names" which we access here.
        $data=json_decode( $_POST['names'] );
        # The data we want is within the property "name"
        $names=$data->name;
        
        # do something with the data
        foreach( $names as $index => $name )echo $name;
        
        exit();
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <title></title>
    </head>
    <body>
        <script>
        
            const getresponse=(r)=>r.text();
            const callback=(res)=>console.log(res)
            
            const json={
                "name" : [
                    "Alsa", "Alice", "Alas", "Alpha", "Beta", "Bervis", "Bankai", "Celcia", "Celsa", "Ceasar", 
                    "Domino", "Dorito", "David", "Eurius", "Easter", "Ethium", "Fourin", "Flora", "Fifa", "Genius"
                ]
            };
            
            let fd=new FormData();
                fd.set( 'names', JSON.stringify( json ) );// set the property we will access in PHP
                
            fetch( location.href, { method:'post', body:fd })
                .then( getresponse )
                .then( callback )
                .catch( alert ) 
        </script>
    </body>
</html>

相关问题