使用http post请求传递有关事件更改的参数

时间:2016-06-17 07:05:48

标签: javascript php jquery twitter-bootstrap

我使用bootstrap ON / OFF开关在事件更改时发送http post请求。每当开关将其状态从ON更改为OFF或OFF更改为ON时,都会触发http post请求。是的,它正在发挥作用。但是,我不知道如何通过http post函数($ .post)传递参数。

update_state.php文件接收参数' state'。例如,update_state.php?state = ON将更改数据库中state字段的值。

到目前为止我的代码。

<script type="text/javascript">
         $('input[name="onoffswitch"]').on('switchChange.bootstrapSwitch', function(event, state) {
          console.log(state); // true | false
          $.post("update_state.php",
            {
                state: "state"
            },
            function(data, status){
                console.log("Data: " + data + "\nStatus: " + status);
            });
        });
</script>

编辑:

<?php

require_once("mysqli_connect.php");

if (!$database) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made!" . PHP_EOL;

$state = $_GET['state'];

$sql = "UPDATE devices SET state='$state' WHERE id=1";

if (mysqli_query($database, $sql)) {
    echo "Record updated successfully.";
} else {
    echo "Error updating record: " . mysqli_error($database);
}

mysqli_close($database);
?>

1 个答案:

答案 0 :(得分:3)

尝试:

$('input[name="onoffswitch"]').on('switchChange.bootstrapSwitch', function(event, state) {
    console.log(state); // true | false
    $.post( "update_state.php", { state: state }) // here { state: state } means {parameter-name: parameter-value}
      .done(function( data ) {
        alert( "Data Loaded: " + data );
    });
});