PHP获取Json数组中的键值或值

时间:2015-09-21 19:57:57

标签: php json ajax

我试图获取密钥或值,取决于我通过ajax发送到服务器,但我从PHP返回没有响应,因为我认为它会。

这是我的php。我称之为myphp.php。

<?php

$m_decoded = $_POST['animal'];

$json = '{"Cat" : "Black", 

  "Dog": "Red",

  "Monkey" : "Yellow"

   }';

$obj = json_decode($json, true);
if(array_key_exists($m_decoded, $obj)){
    print $obj[$m_decoded]; 
}else {
    print array_search($obj[$m_decoded], $obj);
}


//$obj = json_decode($json, true);
//if($obj->{$m_decoded} == NULL){
//  print array_search($obj->{$m_decoded});
//}else {
//  print $obj->{$m_decoded}; 
//}
?>

<script>
$(function() {
    //function startAjax() {
      $(".verse").click(function(e){
          e.preventDefault();

            var cliks = $(this).text();
            $( this ).addClass( "inside" );
            //$("#clickme").text("Calling server");
            $.ajax({
                type: "POST",
                url:"myphp.php",
                data:{"animal" : cliks},
                success:callbackFunction, 
                error:errorFunction
            });
        });
});
    function callbackFunction(data,info) {
                var v = $(".inside").text();
                var val = data;
                //alert(v);
                $(".inside").fadeOut(function(){
                    //alert(v);
                    $(".inside").text(($(".inside").text() == v) ? val : v).fadeIn();
                    $(".inside").removeClass( "inside" );

                });

    }
    function errorFunction(data,info) {
                $(".inside").text("error occurred:"+info);
    }
</script>

我的问题在于php,因为我可以在第一次点击时获得该值,但是第二次点击带有替换值的行时,我希望从服务器获取密钥,但这不是案子。我只想尝试用第一次点击的颜色更改链接的文本,并在第二次点击时返回动物。 任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

更正了键和值(颜色和动物)之间切换的代码:

$obj = json_decode($json, true);
if(array_key_exists($m_decoded, $obj)){
    print $obj[$m_decoded]; 
} else {
    print array_search($m_decoded, $obj);
}

在第二种情况下,您必须在$m_decoded中搜索$obj,而不是$obj[$m_decoded]