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条)

报告相同问题?

悬赏问题

  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗