dongtao5104 2013-09-07 01:13
浏览 54
已采纳

如何从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>
  • 写回答

3条回答 默认 最新

  • douzi2785 2013-09-07 01:32
    关注

    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>";
            }
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?