表单提交时JQuery多个POST

时间:2011-12-14 18:25:45

标签: javascript jquery

我正在尝试将表单提交给表单提交中的两个不同脚本。提交表单的ScriptA将在提交时重定向。 ScriptB不会给出任何类型的响应,只需写下给定的信息。

我无法让提交工作,我对JQuery不是很有经验,这是我的第一次,所以我希望有人可以指出为什么我的表单没有用JQUERY正确提交。

Html的身体:

<script type="text/javascript">
$(document).ready( function(){
    $('#submit').click(function(){
    //Send data to the email script
    $.post( 'authenticate.php', $('Auth').serialize(), function(data, textStatus) {
        //data is the result from the script
        alert(data);
    });

    //Send data to the other script
    $.post( 'http://Service3.com/j_security_check', $('Auth').serialize(), function(data, textStatus) {
        //data is the result from the script
        alert(data);
    });
    });
});
</script>

html表格形式:

<form action=authenticate.php method=post name=Auth id="form" class="appnitro">
 <div class="form_description"><h2>Login</h2></div>
<ul>
    <li id="li_1" >
        <label class="description" for="element_1">Username </label>
        <div>
        <input id="element_1" name="j_username" class="element text medium" type="text" maxlength="255" value=""/>
        </div>
    </li>

    <li id="li_2" >
        <label class="description" for="element_2">Password </label>
        <div>
        <input id="element_2" name="j_password" class="element text medium" type="password" maxlength="255" value=""/>
        </div>
    </li>

    <li class="buttons">
     <input id="saveForm" class="button_text" type="submit" name="submit" id="submit" value="Log In" />
    </li>
</ul>
</form>

我有一个主题问题是如何修复代码的格式?每当我在这里发布我的代码时,我总会得到很大的缩进。

2 个答案:

答案 0 :(得分:3)

$(document).ready( function(){

  $('#form').submit(function(){

    $.ajax({
      type: 'POST',
      async: false,
      url: "your_url_1",
      data: $(this).serialize(),
      success: function(data, status, xhr){
        alert('ok');
      },
      error: function(xhr, status, err) {
        alert(status + ": " + err);
      }
    });

    $.ajax({
      type: 'POST',
      async: false,
      url: "your_url_2",
      data: $(this).serialize(),
      success: function(data, status, xhr){
        alert('ok');
      },
      error: function(xhr, status, err) {
        alert(status + ": " + err);
      }
    });

  });

});

答案 1 :(得分:1)

您的代码存在一些问题。为什么不绑定到表单的click事件,而不是绑定到提交按钮的submit事件。此外,当您序列化表单时,您希望定位表单,并选择$('Auth'),它将尝试选择任何Auth标签(不存在)。

$('#form').submit(function(){
    //Send data to the email script
    $.post( 'authenticate.php', $(this).serialize(), function(data, textStatus) {
        //data is the result from the script
        alert(data);
    });
    return false;//this stops the form from submitting normally
});

您的第二个$.post()看起来正在将表单提交发送到用户当前所在的域的其他域。您只能使用JSONPhttp://api.jquery.com/jquery.ajax执行此操作(搜索JSONP,您会找到有关如何执行此操作的绝佳信息)