使用jQuery在DIV中提交表单

时间:2022-11-23 19:48:43

I'm referring to a problem similar to the one in this post, because the solution described there doesn't work for me.

我指的是一个类似于这篇文章中的问题,因为上面描述的解决方案对我不起作用。

The starting point is a HTML page (called profile) with jQuery UI tabs:

起点是一个带有jQuery UI选项卡的HTML页面(称为profile):

<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>

The HTML rendered within the DIV is:

在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>

In addition, I use the following JS script (based on the post linked in the introduction):

另外,我使用了以下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
});

The record is submitted, but the behavior is different depending on the browser:

记录被提交,但是根据浏览器的不同行为是不同的:

  • IE, Firefox, Opera: correct content into DIV, excellent!

    IE, Firefox, Opera:正确的内容到DIV,太棒了!

  • Safari, Chrome: correct content, but the entire page is refreshed with the results

    Safari浏览器,Chrome:正确的内容,但是整个页面都会被结果刷新

Please let me know what I'm doing wrong. Many many thanks!

请让我知道我做错了什么。很多谢谢!

UPDATE 1: The DIV named pwd-settings is created by the tab interface only. Please note that the behavior is the same, even if I add it to the HTML (with <div id ="pwd-settings"></div>).

更新1:命名为pwd-settings的DIV仅由选项卡界面创建。请注意,这个行为是相同的,即使我将它添加到HTML (

)。

UPDATE 2: I also removed the JavaScript above and all browsers became "correct content, but the entire page is refreshed" = "old URL, new content". As soon as I added the JavaScript to the HTML page rendered within the DIV, it started working in the browser described above. Hence I see two possible error reasons:

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

1) The JS is simply not executed in the browsers having errors or

1)如果浏览器有错误或错误,则不执行JS

2) The JS within the DIV doesn't work because it addresses a DIV which only exists outside

2)DIV中的JS不能工作,因为它只处理一个只存在于外部的DIV。

6 个解决方案

#1


1  

jQuery's serialize() function only gets <input> elements. A link element is not an input. Calling $(this).serialize() won't add the value of the <a> element to your data.

jQuery的serialize()函数只获取元素。链接元素不是输入。调用$(this).serialize()不会将元素的值添加到您的数据中。

You need to add an <input> element to hold that data. Perhaps try

您需要添加一个元素来保存该数据。或许你可以尝试

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

EDIT: Can you post the full html? From the looks of it right now, your selectors won't select the form because it doesn't even have an id property....

编辑:你能发布完整的html吗?从现在看起来,你的选择不会选择形式,因为它甚至没有一个id属性....

#2


1  

Here's my guesses --

这是我的猜测

First, you don't have an 'action' attribute on your form. So the JS line for $(this).attr('action') doesn't return anything. I'm not sure how jQuery Ajax handles that.

首先,表单上没有“动作”属性。所以$(this).attr('action')的JS行不会返回任何东西。我不确定jQuery Ajax如何处理这个问题。

But I think the real issue is the example.php script and how it's handling your calls. I'm no Ajax expert, but that is not the way I would do it at all. If you take out the showFile() stuff, and just echo $_REQUEST['cmd'], does it work?

但我认为真正的问题是这个例子。php脚本以及它如何处理您的调用。我不是Ajax专家,但我根本不会这么做。如果取出showFile()内容,只回显$_REQUEST['cmd'],那么它是否有效?

Other than that, I'm out of ideas. But it's not a quirk of the browsers, it's an issue with your code, I can say that much.

除此之外,我没有主意了。但这不是浏览器的问题,这是你的代码的问题,我可以这么说。

#3


1  

I finally found out the reason: some browsers (namely the ones having issues) behave differently when the JS described in the question is loaded due to the fact the form does not exist yet because the content of the tab is loaded later on via Ajax.

我最终找到了原因:当加载问题中描述的JS时,一些浏览器(即存在问题的浏览器)的行为不同,因为表单还不存在,因为选项卡的内容稍后将通过Ajax加载。

Hence the solution is to create a JS function instead of the code above and adapt the button (submit becomes button, introducing onClick):

因此解决方案是创建一个JS函数而不是上面的代码,并调整按钮(提交变成按钮,引入onClick):

<input type="button" value=" Apply " onClick="callMyFunction()" />

This is handled correctly by Safari and Chrome then too.

Safari和Chrome也能正确处理这个问题。

Many thanks to all participants!

非常感谢所有的参与者!

#4


0  

The easiest way to solve this would be to add a hidden input to your form:

解决这个问题最简单的方法是在表单中添加一个隐藏的输入:

<input type="hidden" name="cmd" value="checkPassword" id="cmd-field" />

If this value needs to change depending on which tab is showing (though it doesn't sound like that's the case), you can change it dynamically when the tab is toggled:

如果这个值需要根据显示的选项卡进行更改(虽然听起来不像这样),可以在选项卡切换时动态更改:

$("#invent-an-id-for-the-link-that-switches-to-this-tab").click(function() {
    $("#cmd-field").value("checkPassword");
});

#5


0  

Safari has excellent web dev tools. If you're running the Windows version you have to enable it in Preferences -> Advanced. Open up the Web Inspector and check your request/response headers.

Safari拥有优秀的web开发工具。如果你运行的是Windows版本,你必须在首选项中启用它——>高级。打开Web检查器,检查请求/响应头。

This won't point directly to the solution but right now there isn't much to go on. Get those headers and keep us updated!

这不会直接指向解决方案,但现在没有什么可做的了。获取这些头信息并让我们更新!

#6


0  

Looks like you're handler is not being loaded for the latter browsers... Since the content of the form is dynamic you've gotta make sure is loaded into the DOM before setting the form's handler.

看起来你的处理器没有为后一种浏览器加载……由于表单的内容是动态的,所以在设置表单处理程序之前,必须确保已加载到DOM中。

You have 2 possible solutions.

有两种可能的解。

First, once the tab content is loaded, load the piece of script you posted (check jquery doc for tab event load: http://docs.jquery.com/UI/Tabs#event-load).

首先,一旦加载了选项卡内容,加载您发布的脚本(检查jquery doc是否加载选项卡事件:http://docs.jquery.com/UI/Tabs#event-load)。

Second, use jquery live event on button click (currently event submit is not supported). Check out: http://docs.jquery.com/Events/live

其次,在单击按钮时使用jquery live事件(当前不支持事件提交)。查阅:http://docs.jquery.com/Events/live

The code for the second solution:

第二种解决方案的代码:

$('#subform input:submit').live('click', 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 });

});返回错误;//取消原活动以防止提交表格);

First solution

第一个解决方案

These are the changes I made to get it to work:

这些是我为了让它工作所做的改变:

  1. Remove generic.js from tpl_overview.tpl
  2. 删除一般。js从tpl_overview.tpl
  3. Change the code (@tpl_overview.tpl):

    更改代码(@tpl_overview.tpl):

    $(function() { $('#tabs').tabs() });

    $(函数(){ $(“#标签”).tabs()});

with this code:

这段代码:

 $(function() {
     $("#tabs").tabs( {
        load: function(event, ui) {
           // load specific script to handle form submission
           if ($(ui.tab).attr('href') == '#pwd-settings') {
              $.getScript('generic.js');
           }
        }
     } );
  });

This will load and execute the generic.js script after the content of the tab is loaded.

这将加载并执行泛型。加载选项卡内容后的js脚本。

If you see yourself doing this too many times, perhaps you can name your scripts after the tab link names...

如果您多次看到自己这样做,也许您可以在标签链接名称之后命名您的脚本……

Let us know if it worked!

让我们知道它是否有效!

#1


1  

jQuery's serialize() function only gets <input> elements. A link element is not an input. Calling $(this).serialize() won't add the value of the <a> element to your data.

jQuery的serialize()函数只获取元素。链接元素不是输入。调用$(this).serialize()不会将元素的值添加到您的数据中。

You need to add an <input> element to hold that data. Perhaps try

您需要添加一个元素来保存该数据。或许你可以尝试

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

EDIT: Can you post the full html? From the looks of it right now, your selectors won't select the form because it doesn't even have an id property....

编辑:你能发布完整的html吗?从现在看起来,你的选择不会选择形式,因为它甚至没有一个id属性....

#2


1  

Here's my guesses --

这是我的猜测

First, you don't have an 'action' attribute on your form. So the JS line for $(this).attr('action') doesn't return anything. I'm not sure how jQuery Ajax handles that.

首先,表单上没有“动作”属性。所以$(this).attr('action')的JS行不会返回任何东西。我不确定jQuery Ajax如何处理这个问题。

But I think the real issue is the example.php script and how it's handling your calls. I'm no Ajax expert, but that is not the way I would do it at all. If you take out the showFile() stuff, and just echo $_REQUEST['cmd'], does it work?

但我认为真正的问题是这个例子。php脚本以及它如何处理您的调用。我不是Ajax专家,但我根本不会这么做。如果取出showFile()内容,只回显$_REQUEST['cmd'],那么它是否有效?

Other than that, I'm out of ideas. But it's not a quirk of the browsers, it's an issue with your code, I can say that much.

除此之外,我没有主意了。但这不是浏览器的问题,这是你的代码的问题,我可以这么说。

#3


1  

I finally found out the reason: some browsers (namely the ones having issues) behave differently when the JS described in the question is loaded due to the fact the form does not exist yet because the content of the tab is loaded later on via Ajax.

我最终找到了原因:当加载问题中描述的JS时,一些浏览器(即存在问题的浏览器)的行为不同,因为表单还不存在,因为选项卡的内容稍后将通过Ajax加载。

Hence the solution is to create a JS function instead of the code above and adapt the button (submit becomes button, introducing onClick):

因此解决方案是创建一个JS函数而不是上面的代码,并调整按钮(提交变成按钮,引入onClick):

<input type="button" value=" Apply " onClick="callMyFunction()" />

This is handled correctly by Safari and Chrome then too.

Safari和Chrome也能正确处理这个问题。

Many thanks to all participants!

非常感谢所有的参与者!

#4


0  

The easiest way to solve this would be to add a hidden input to your form:

解决这个问题最简单的方法是在表单中添加一个隐藏的输入:

<input type="hidden" name="cmd" value="checkPassword" id="cmd-field" />

If this value needs to change depending on which tab is showing (though it doesn't sound like that's the case), you can change it dynamically when the tab is toggled:

如果这个值需要根据显示的选项卡进行更改(虽然听起来不像这样),可以在选项卡切换时动态更改:

$("#invent-an-id-for-the-link-that-switches-to-this-tab").click(function() {
    $("#cmd-field").value("checkPassword");
});

#5


0  

Safari has excellent web dev tools. If you're running the Windows version you have to enable it in Preferences -> Advanced. Open up the Web Inspector and check your request/response headers.

Safari拥有优秀的web开发工具。如果你运行的是Windows版本,你必须在首选项中启用它——>高级。打开Web检查器,检查请求/响应头。

This won't point directly to the solution but right now there isn't much to go on. Get those headers and keep us updated!

这不会直接指向解决方案,但现在没有什么可做的了。获取这些头信息并让我们更新!

#6


0  

Looks like you're handler is not being loaded for the latter browsers... Since the content of the form is dynamic you've gotta make sure is loaded into the DOM before setting the form's handler.

看起来你的处理器没有为后一种浏览器加载……由于表单的内容是动态的,所以在设置表单处理程序之前,必须确保已加载到DOM中。

You have 2 possible solutions.

有两种可能的解。

First, once the tab content is loaded, load the piece of script you posted (check jquery doc for tab event load: http://docs.jquery.com/UI/Tabs#event-load).

首先,一旦加载了选项卡内容,加载您发布的脚本(检查jquery doc是否加载选项卡事件:http://docs.jquery.com/UI/Tabs#event-load)。

Second, use jquery live event on button click (currently event submit is not supported). Check out: http://docs.jquery.com/Events/live

其次,在单击按钮时使用jquery live事件(当前不支持事件提交)。查阅:http://docs.jquery.com/Events/live

The code for the second solution:

第二种解决方案的代码:

$('#subform input:submit').live('click', 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 });

});返回错误;//取消原活动以防止提交表格);

First solution

第一个解决方案

These are the changes I made to get it to work:

这些是我为了让它工作所做的改变:

  1. Remove generic.js from tpl_overview.tpl
  2. 删除一般。js从tpl_overview.tpl
  3. Change the code (@tpl_overview.tpl):

    更改代码(@tpl_overview.tpl):

    $(function() { $('#tabs').tabs() });

    $(函数(){ $(“#标签”).tabs()});

with this code:

这段代码:

 $(function() {
     $("#tabs").tabs( {
        load: function(event, ui) {
           // load specific script to handle form submission
           if ($(ui.tab).attr('href') == '#pwd-settings') {
              $.getScript('generic.js');
           }
        }
     } );
  });

This will load and execute the generic.js script after the content of the tab is loaded.

这将加载并执行泛型。加载选项卡内容后的js脚本。

If you see yourself doing this too many times, perhaps you can name your scripts after the tab link names...

如果您多次看到自己这样做,也许您可以在标签链接名称之后命名您的脚本……

Let us know if it worked!

让我们知道它是否有效!