简体   繁体   中英

ajax json php decode

i'm looking for passing params between server and client but i don't find a solution. I've read all the web but i don't find a working solution.

Client Side

function move(column, line) {
$.ajax({
    type: 'POST',
    url: 'index.php?action=setpawn',
    data: {column: column, line: line},
    contentType: "application/json; charset=utf-8",
    async: false,
    success: function(data) {
        alert(data.donnees);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown+textStatus);
    }
});
}

Server Side

$data = json_decode(file_get_contents('php://input'),true);
header('Content-Type:application/json; charset=utf-8');
$response = array('isvalid' => "0" , 'donnees' => $data['column']);
echo json_encode($response);

I can't acces 'column' and 'line' data on the server, and the json response is bad too (sometimes parse error or bad result).

Please help me i can't find a way to make it work... (sorry for my bad english, i'm french and i do the best i can)

jQuery does not JSON-encode by default, but as x-www-form-urlencoded . You need to send

$.ajax({
    type: 'POST',
    url: 'index.php?action=setpawn',
    data: JSON.stringify({column: column, line: line}),
//        ^^^^^^^^^^^^^^
    contentType: "application/json; charset=utf-8"
})

Check at the server side whether file_get_contents('php://input') is what you expect, before json_decode ing it and getting a parse error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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