如何使用AJAX进行POST

时间:2017-02-25 23:22:43

标签: jquery ajax post

我无法弄清楚这一点,我问了几个人,我们很难过。我通常不会使用AJAX,但在这种情况下我觉得我必须这样做。

其他人可以用这个吗?

<!DOCTYPE>
<html>
  <body>
  <center>
  <br>
  <br>
  <br>
  <form>
    Tell your device what to do!<br>
    <br>
    <input type="radio" name="arg" value="on">Turn the LED on.</input>
    <br>
    <input type="radio" name="arg" value="off">Turn the LED off.</input>
    <br>
    <input type="radio" name="arg" value="blueSwap">Toggle Blue.</input>
    <br>
    <input type="radio" name="arg" value="allSwap">Toggle All.</input>
    <br>
    <br>
    <input type="submit" value="Do it!"/>
  </form>
  <br>
  </center>

  <script
    src="https://code.jquery.com/jquery-2.2.4.min.js"
    integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
    crossorigin="anonymous"></script>

  <script>
    let url = 'https://api.particle.io/v1/devices/2f0021000547353138383138/led?access_token=150a347fb4277975913f5dfe24e2fb739171b3c5'

    $('form').on('submit', (e) => {
      e.preventDefault()
      let data = $(this).serialize()
      $.ajax({
        url: url,
        type: 'POST',
        data: data
      }).done(() => {
        console.log('sent')
      })
    })
    </script>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

并非所有浏览器都支持Arrow Function。你可以尝试使用常规的ECMAScript 5,看看它是否有效。

演示:https://jsfiddle.net/rab5j0ua/

请确保输入标记为<input.../>而不是<input...>...</input>

<!DOCTYPE>
<html>
<body>
    <center>
        <br>
        <br>
        <br>
        <form>
            Tell your device what to do!<br>
            <br>
            <input type="radio" name="arg" value="on" />Turn the LED on.
            <br>
            <input type="radio" name="arg" value="off" />Turn the LED off.
            <br>
            <input type="radio" name="arg" value="blueSwap" />Toggle Blue.
            <br>
            <input type="radio" name="arg" value="allSwap" />Toggle All.
            <br>
            <br>
            <input type="submit" value="Do it!" />
        </form>
        <div id="result"></div>
        <br>
    </center>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"
            integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous"></script>

    <script>
        var url = 'https://api.particle.io/v1/devices/2f0021000547353138383138/led?access_token=150a347fb4277975913f5dfe24e2fb739171b3c5'

        $('form').submit(function (e) {
            e.preventDefault();
            var data = $(this).serialize();
            $.ajax({
                url: url,
                type: 'POST',
                data: data
            })
                .success(function (result) {
                    $('#result').text(JSON.stringify(result));
                    console.log(result);
                });
        });
    </script>
</body>
</html>

答案 1 :(得分:0)

此代码适用于我。

也许将你的脚本包装成:

$(function(){

...

});

这将等待运行代码(从而绑定submit事件),直到加载整个页面。可能是您的<form>在绑定事件之前未加载。但是,正如我所说,我可以在开发人员工具的网络选项卡中看到POST被发送到服务器。