如何从php发送变量值到js [复制]

This question already has an answer here:

I want to send variable from php to js . I want to work this file like that js sends value php file then php works on this code and return again variable like true or false after that js controls and shows something users.I am Sorry for my poor English :D

<?php 

if(!empty($_POST['a']))
{
    $value=1;
    echo '{"a":"'.$value.'"}';
}
else
{
    ?>  
    <script src="assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
    <script src="assets/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript></script>
    <script>
    function sendValue($page,$value)
    {
        $.post($page, $value , function(data)
        {
            if(data.a==1)
           {
                alert("its work");
           }
           else
           {
                alert("oh no Houston  we have a problem !!");
           }
    }
    )};
    </script>
    <a href="#"  onclick='sendValue("a.php",{a:"1"});' >blabla</a>
    <?php 
}
?>
</div>

If I understand correctly, you want to send data to PHP, then have PHP return data accordingly. Here is what I use to make an ajax call:

var sendData = "action=do_action";
sendData += "&value=" + $("input.value").val();

$.ajax({
    url: "post.php",//Page to send our data to
    global: false,
    type: "POST",
    data: sendData,
    dataType: "html",
    async:false,
    success: function(data){
        //We could return JSON and then just parse that, but I usually just return values like this

        //create jquery object from the response html
        var $response=$(data);

        var results = $response.filter('div.results').text();//Or .html() if we want to return HTML to show                     

        if (results == "true") {
            alert("it works");
        }else{
            var reason= $response.filter('div.reason').text();
            alert(reason);
        }
    }
});

And the PHP would look like:

<?php
    $action = $_POST['action'];

    if ($action == "do_action") {
        if (true) {
            echo "<div class='result'>true</div>";
        }else{
            echo "<div class='result'>false</div>";
            echo "<div class='reason'>Houston, we have a problem!</div>";
        }
    }
?>
str=$("input.classname").val();

or

str=$("input#idname").val();

it is inside js

and the easy way to send information by hidden input like this

<input type="hidden" class="classname" value="<?php echo "here the value you want to send"; ?>" />

Which is the active directory in this case? Is it the one which contains a.php?

Also, you are sending back a string. You must convert that using JSON.parse().

Your response is a string, so it does not have an 'a'.