weixin_33743703 2018-04-02 18:21 采纳率: 0%
浏览 38

WordPress的:获取JSON-JS到PHP

I have a JSon object in a js page. I want to receive this data in a php page.

Page: ajax.js:

var campi={0: {1: ' ', 2: ' ', 3: ' '}};
campi=JSON.stringify(campi); //thank you @Musa
$.ajax({
    url: example_ajax_obj.ajaxurl,
    type: 'POST',
    data: {
        'action': 'example_ajax_request',
        'campi' : campi
    },
    success:function(data) {
        console.log(campi);             
    },
    error: function(errorThrown){
        console.log(errorThrown);
    }
});

Page: page.php

function example_ajax_request() {
    $campi = $_POST['campi']; 
    echo "<script>console.log( 'Debug Objects: " . $campi . "' );</script>";
    $json_data = json_decode($campi, true);
    echo "<script>console.log( 'Debug Objects: " . $json_data . "' );</script>";
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_enqueue_scripts', 'example_ajax_request' );

Consolle shows me:

-Debug Objects: //due to echo "console.log( 'Debug Objects: " . $campi . "' );";

-Debug Objects: Array //due to echo "console.log( 'Debug Objects: " . $json_data . "' );";

{0: {1: ' ', 2: ' ', 3: ' '}}

I can't figure the reason why it doesn't work and I don't know how to debug. Thank you guys

  • 写回答

1条回答 默认 最新

  • MAO-EYE 2018-04-02 18:27
    关注

    campi is not JSON, you'll have to convert it to JSON before you send it

    $.ajax({
        url: example_ajax_obj.ajaxurl,
        type: 'post',
        data: {
            'action': 'example_ajax_request',
            'campi' : JSON.stringify(campi) //<-- here
        },
        success:function(data) {
            console.log(campi);             
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
    
    评论

报告相同问题?