doulei3488 2014-04-28 17:09
浏览 46
已采纳

使用AJAX执行PHP代码

I am currently working on a little project for my PLC. I use PHP to open a connection to said PLC.

I have created a little website to make interacting easier.

What I want to include on this website is a couple of toggles to send different commands to the device.

I want this done without having to reload the website, so what my researches came up with was to use AJAX.

Now I have tried multiple tutorials on AJAX onclick events using normal buttons and toggles....but none of them gave me the results I wanted.

What would be the easiest way to accomplish what I need?

When the button is pressed I need to execute this php code

      $plc->WriteBit("E", 0, 0, 0, 1);

When the button is pressed again I need this to execute

      $plc->WriteBit("E", 0, 0, 0, 0);

All this should work without reloading the site.

Like I said I have really no clue how to parse this php code directly from AJAX. I hope someone can push me in the correct direction!

Thanks!

  • 写回答

2条回答 默认 最新

  • dqz30992 2014-04-28 17:23
    关注

    Try something like this:

    MULTIPLE BUTTONS/ADDRESSES:

    <input type='button' name='writeA' value='WRITE BIT A' data-bit='1' data-address='000' class='plc'>
    <input type='button' name='writeB' value='WRITE BIT B' data-bit='0' data-address='001' class='plc'>
    <div id='output'></div>
    

    jQuery:

    $(document).on('click', 'input.plc', function() {
        var bit = parseInt($(this).attr('data-bit'));
        var address = $(this).attr('data-address');
        $('#output').load('plc.php', {'bit':bit, 'address':address});
        $(this).attr('data-bit', bit^1);    // xor bit to toggle value
    });
    

    PHP script (plc.php):

    $bit = isset($_POST["bit"]) ? $_POST["bit"] : 0;
    $address = isset($_POST["address"]) ? $_POST["address"] : '000';
    $lst_address = str_split($address);
    $plc->WriteBit("E", $lst_address[0], $lst_address[1], $lst_address[2], $bit);    // or use an 'if' or 'switch' statement    
    echo $bit;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加