【问题标题】:Post form with Ajax and jQuery使用 Ajax 和 jQuery 发布表单
【发布时间】:2011-05-31 04:37:33
【问题描述】:

开始学习 Ajax(和 jQuery),我遇到了 post 表单数据的问题,我自己无法解决。

首先,这是我收集数据、发布数据并将其显示在新页面上的简单示例:

<!-- index.html -->
<form id="myForm" action="test.php" method="post"> 
<input type="checkbox" id="ch1" name="Ch1" value="1">Check Box 1 <br />
<input type="checkbox" id="ch2" name="Ch2" value="2">Check Box 2 <br />
<input type="submit" id="myButton" />
</form>

<?php
// test.php
print_r($_POST);
?>

然后我尝试使用 Ajax 和 jQuery。我稍微修改了上面粘贴的表格:

<!-- index.html -->
<form id="myForm"> 
<input type="checkbox" id="ch1" name="Ch1" value="1">Check Box 1 <br />
<input type="checkbox" id="ch2" name="Ch2" value="2">Check Box 2 <br />
<input type="button" id="myButton" value="Submit"/>
</form>

这里是 jQuery 函数:

// script.js

$(document).ready(function () {
    $("#myButton").click(function () {
        $.ajax({
            cache: false,
            type: 'POST',
            url: 'test.php',
            data: $("#myForm").serialize()
        });
    });
});

我的问题是,如何重新实现 jQuery 函数以在 test.php 选项卡中回显结果?我爬了很多资源,但我没有找到任何解决方案。

提前感谢您的任何指点。

最好的,安德烈

【问题讨论】:

  • 什么“标签”? test.php 是你的目标脚本。

标签: php jquery ajax forms post


【解决方案1】:

您将需要一个 success 回调,我假设它是一些 HTML...

$(document).ready(function(){ 
    $("#myButton").click(function() { 
        $.ajax({
        cache: false,
        type: 'POST',
        url: 'test.php',
        data: $("#myForm").serialize(),
        success: function(response) {
            $("#someElement").html(response);
        }
        });
    }); 
});

【讨论】:

  • 但这会在我的 index.html 中显示 $_POST。我想要的是打开 test.php 并在那里呈现结果。
【解决方案2】:

试试这个。

$(document).ready(function(){ 
    $("#myButton").click(function() { 
        $.ajax({
        cache: false,
        type: 'POST',
        url: 'test.php',
        data: $("#myForm").serialize(),
        success: function(data){
        alert(data);
        }
        });
    }); 
});

【讨论】:

    【解决方案3】:

    我相信您正在寻找 .ajax 选项参数中的 success。

    $.ajax({
      ...
      success: function(d){
        alert(d);
      }
    });
    

    【讨论】:

    • 但这只会显示一条警报消息。我想要的是打开 test.php 并在那里呈现结果。
    • 我认为你错过了 AJAX 的意义。如果您正在寻找打开的窗口,AJAX 不是您的选择。 AJAX 用于“无缝集成”,无需离开页面即可履行职责。对于您要执行的操作,我建议使用默认表单操作(并且可能添加 target="_blank" 以便它在新窗口中提交。
    • 好的,很好。被你的措辞弄糊涂了。现在,只需将其绑定到一个元素(如&lt;div id="myElement"&gt;&lt;/div&gt;)并使用$('#myElement').html(d); 之类的东西将结果放在那里(代替警报)。
    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多