简体   繁体   中英

Decode JSON with PHP

Can some one tell why this simple JSON with JqUERY doesn't work for me?

I have this JS code,

var jsonParam = <? $json = $_SESSION['searchSess']; echo json_encode($json);?>;
jsonParam = JSON.stringify(jsonParam);
$(document).ready(function(){
      $.post("searching.php?rdr=search", {data: jsonParam,}, function (data){
        alert(data)
    })
});

And Here is the PHP code,

$data = json_decode($_POST['jsonParam'], true);
var_dump($data);

And the response is null or nothing,

can please someone help whats wrong here?

Thank you

您需要$_POST['data'] ,而不是$_POST['jsonParam']

jsonParam was the JavaScript variable, but it was posted to PHP as $_POST['data'] since you passed {data: jsonParam} into the $.post .

// Instead:
$data = json_decode($_POST['data'], TRUE);
var_dump($data);

{jsonParam: jsonParam,}代替{data: jsonParam,}

$data = json_decode($_POST['jsonParam'], true); should be $data = json_decode($_POST['data'], true);

Try the following:

JS:

var jsonParam = <? 
    $json = $_SESSION['searchSess']; 
    $json['longitude'] = (string) $json['longitude'];
    $json['latitude'] = (string) $json['latitude'];

    echo json_encode($json);
?>

$(document).ready(function(){
      $.post("searching.php?rdr=search", {data: jsonParam }, function (data){
        alert(data)
    })
});
 

PHP:

$data = json_decode($_POST['data'], true);
var_dump($data);

I suspect your longitude and latitude fields are not being parsed correctly as floats.

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