使用 JQuery 移动按钮触发休息 API 呼叫

Triggering a Rest API call with a JQuery Mobile button

这很简单,但我的 JS 有点生疏.. 我试图通过按 JQuery 移动元素来触发获取请求。 我可以看到按钮,但无法执行实际的获取请求

<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>
<form>
    <label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
    <p><input type="checkbox" data-role="flipswitch" name="flip-checkbox-1" id="generator_button"></p>
</form>
</body>

<script>
$("p").on("tap",function(){
  $.ajax({
    'url' : '192.168.8.110:5000/generator_on',
    'type' : 'GET',
    'success' : function(data) {
      if (data == "success") {
        alert('request sent!');
      }
    }
  });
</script>

您 javascript 的最后一行缺少 });

您的 javascript 代码应如下所示

$("p").on("tap",function(){
  $.ajax({
    'url' : '192.168.8.110:5000/generator_on',
    'type' : 'GET',
    'success' : function(data) {
      if (data == "success") {
        alert('request sent!');
      }
    }
  });
});

请注意:在您的标记中有一个 Flip switch 类型 checkbox,而不是按钮,所以我相信您最好检查底层 checkbox 的状态坚持参加 tap 活动。

参考:jQuery Mobile Flip switch

此外,如果您能为所有内容提供一个 JQM 页面结构,那就太好了。

这是一个例子:

function sendRequest() {
  $.ajax({
    'url': '192.168.8.110:5000/generator_on',
    'type': 'GET',
    'success': function(data) {
      if (data == "success") {
        alert('request sent!');
      }
    }
  });
}

$(document).on("change", "#generator_button", function() {
  var state = $("#generator_button").prop("checked");
  if (state === true) {
    // Flip switch is on
    console.log("Request sent.");
    //sendRequest(); // uncomment
  } else {
    // Flip switch is off
    //...endpoint _off
  }
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
  </head>
<body>
  <div id="page-one" data-role="page">
    <div data-role="header" data-position="fixed">
      <h1>Header</h1>
    </div>
    <div role="main" class="ui-content">
      <label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
      <input type="checkbox" data-role="flipswitch" name="generator_button" id="generator_button">
    </div>
    <div data-role="footer" data-position="fixed">
      <h1>Footer</h1>
    </div>
  </div>
</body>
</html>

好的,所以我不得不将 url 更改为:'http://192.168.8.110:5000/generator_on 并在没有我提到的广告拦截的浏览器上测试它以使其工作!