$ .post到远程网站然后提交默认操作

时间:2016-04-20 15:51:43

标签: javascript html

function post()
{
   var cvs = $('#client-nbr').val();
   var cs = $('#cs').val();
   $.post('http://sitea.com/a.php',{postcvs:cvs,postch1:cs});
   return false;
}

调用函数onsubmit:

<form action="http://siteb.com/b.php" method="post" id="formID" onsubmit="post()">
  <input type="text" name="client-nbr" id="client-nbr" /> <br>
  <input type="text" name="cs" id="cs" /> <br>
  <button type="submit" name="submit" id="submit">subscribe</button>
</form>

我想等待function post()完成发布之后提交默认操作吗?

3 个答案:

答案 0 :(得分:2)

<form action="http://siteb.com/b.php" method="post" id="formID">
    <input type="text" name="client-nbr" id="client-nbr" /> <br>
    <input type="text" name="cs" id="cs" /> <br>
    <!-- http://stackoverflow.com/a/23968244/2240375 -->
    <button type="submit" name="submit_btn" id="submit_btn">subscribe</button>
</form>
<script>
    $("#formID").submit(function (objEvent) {
        // Prevent your form submition
        objEvent.preventDefault();
        $.ajax({
            type: 'POST',
            url: "http://sitea.com/a.php",
            data: {
                postcvs: $('#client-nbr').val(),
                postch1: $('#cs').val()
            },
            success: function (strResponseData) {
                // After successfull ajax request submit the form
                $("#formID")[0].submit();
            }
        });
    })
</script>

答案 1 :(得分:2)

$.post()返回promise object。 promise对象具有各种方法来挂钩有关完成任务的事件,例如“done”。如果我真的需要等到外部ajax调用完成后再进行我的表单发布,我会做以下事情:

的Javascript

$('#my-button').click( function( e) {
    e.preventDefault();
    var cvs = $('#client-nbr').val();
    var cs = $('#cs').val();
    $.post('http://sitea.com/a.php',{postcvs:cvs,postch1:cs}).done( function() {
        $(e.target).closest("form").submit();
    });

    return false;
}

HTML

<form action="http://siteb.com/b.php" method="post" id="formID">
    <input type="text" name="client-nbr" id="client-nbr" /> <br>
    <input type="text" name="cs" id="cs" /> <br>
    <button id="my-button" type="submit" name="submit" id="submit">subscribe</button>
</form>

但是,您似乎不太可能需要等待发布结果。如果没有时间问题,你不需要对帖子结果做任何事情,我建议你简单的解雇并忘记。

答案 2 :(得分:1)

如果此js脚本在站点A托管,您可以在那里发布:

                $.ajax({
                    url: 'http://sitea.com/a.php',
                    type: 'post',
                    data: {"postcvs":cvs, "postch1":cs},
                    success: function(data, status) {
                        console.log("success!");
                    }, error: function(xhr, desc, err) {
                        console.log(xhr);
                        console.log("Details: " + desc + "\nError:" + err);
                    }
                }); // end ajax call

但是,如果您的脚本位于网站B上,则您只能发布到网站B. More on the same origin policy here