如何使用 AJAX 发送帖子数据,当前解决方案不起作用

所以我有一个按钮,我想使用 ajax 将发布数据发送到 PHP 文档,然后重新加载页面。


这是按钮:


  <button value="ON" id="send" class="btn btn-block btn-primary btn-sm">ON</button><br>

这是AJAX


    <script>

    $('#send').click(function() {

    var val1 = $('Online').text();;

    $.ajax({

        type: 'POST',

        url: 'stat.php',

        data: { stat: val1 },

        success: function(response) {

            window.location.reload();

        }

    });

});

}

    </script>


偶然的你
浏览 90回答 2
2回答

守着一只汪

请删除window.location.reload();您没有从 ajax 获得响应,因为在获取数据之前页面已重新加载或者,如果您想在页面成功后重新加载页面,请使用以下代码:&nbsp; <script>&nbsp; &nbsp; $('#send').click(function() {&nbsp; &nbsp; var val1 = "asdas";&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; url: 'stat.php',&nbsp; &nbsp; &nbsp; &nbsp; data: { stat: val1 },&nbsp; &nbsp; &nbsp; &nbsp; success: function(response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(response);&nbsp; &nbsp; &nbsp; &nbsp; if(response){ // if true (1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;setTimeout(function(){// wait for 5 secs(2)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;location.reload(); // then reload the page.(3)&nbsp; &nbsp; &nbsp; }, 5000);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});&nbsp; &nbsp; </script>这肯定会帮助你!

慕尼黑5688855

您可以根据jQuery官方文档文档$.ajax使用新的使用done()方法,如果请求成功发送,将触发该方法。假设元素val1如下$('#send').on('click', function() {&nbsp; var val1 = $('#online').text();&nbsp; $.ajax({&nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; url: 'http://example.com/stat.php',&nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; stat1: val1&nbsp; &nbsp; },&nbsp; }).done(function(response) {&nbsp; &nbsp; window.location.reload();&nbsp; });});<input type="text" id="online" value="test">
打开App,查看更多内容
随时随地看视频慕课网APP