php - 使用 jQuery 在 DIV 中提交表单

标签 php jquery ajax html webforms

我指的是类似于 the one in this post 的问题,因为那里描述的解决方案对我不起作用。

起点是一个带有 jQ​​uery UI 选项卡的 HTML 页面(称为配置文件):

<div id="tabs"> 
    <ul> 
        <li><a href="#realtab">Foo Bar</a></li> 
        <li><a href="?cmd=changePassword" title="pwd-settings">
                        <span> Dynamic tab </span>
            </a></li>
    </ul>
</div>

在 DIV 中呈现的 HTML 是:

<form method="post" id="subform" action="http://myhost.com/example.php">
    <input type="hidden" name="cmd" value="submitChangedPassword">

    <dl>
        <dt>PWD1</dt>
        <dd><input type="password" name="password" /></dd>

        <dt>PWD CHK</dt>
        <dd><input type="password" name="passwordChk" /></dd>

        <dt>&nbsp;</dt>
        <dd><input type="submit" value=" Apply " /></dd>
    </dl>
</form>

此外,我使用以下 JS 脚本(基于简介中链接的帖子):

$('#subform').submit(function() { // catch the form's submit event - should I use the form id?
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
            $('#pwd-settings').html(response); // update the DIV - should I use the DIV id?
        }
});
return false; // cancel original event to prevent form submitting
});

记录已提交,但行为因浏览器而异:

  • IE、Firefox、Opera:将内容正确写入 DIV,非常好!

  • Safari、Chrome:内容正确,但整个页面刷新并显示结果

请让我知道我做错了什么。非常感谢!

更新 1: 名为 pwd-settings 的 DIV 仅由选项卡界面创建。请注意,即使我将其添加到 HTML(使用 <div id ="pwd-settings"></div> ),行为也是相同的。

更新2:我还删除了上面的JavaScript,所有浏览器都变成“正确内容,但整个页面刷新”=“旧URL,新内容”。当我将 JavaScript 添加到 DIV 中呈现的 HTML 页面后,它就开始在上述浏览器中工作。因此我看到两个可能的错误原因:

1) JS 在有错误的浏览器中根本不执行

2) DIV 内的 JS 不起作用,因为它处理的是仅存在于外部的 DIV

最佳答案

jQuery 的 serialize()函数仅获取 <input>元素。链接元素不是输入。调用$(this).serialize()不会添加 <a> 的值元素到您的数据。

您需要添加 <input>保存该数据的元素。也许尝试一下

<input type="hidden" value="changePassword" name="cmd" />

编辑:你能发布完整的 html 吗?从现在的情况来看,您的选择器不会选择该表单,因为它甚至没有 id 属性......

关于php - 使用 jQuery 在 DIV 中提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1266697/

相关文章:

javascript - 为什么此代码会发出警报 "undefined"

php - 在 yii2 中验证 parent_id

php - 如何使用 Mysql 和 PHP 获取当前本地时间?

JavaScript:如何在更改src后获取图像的高度

javascript - 下载jsp项目

Javascript、jquery、ajax url 查询字符串重写

PHP正则表达式跨多行搜索

php - 我可以在 eval() 中执行 mysql_query 吗?

javascript - 我的程序只获取数组的第一个值,我需要所有

javascript - 点击事件未注册