jquery - 同步提交帖子(不是ajax)

ola*_*ndo 16 jquery post synchronous

我有一个页面(page 1)接受发布请求,做一些事情并在最后显示一些数据.

从另一个页面(page 2),我想重定向到page 1单击按钮时,当然发送page 1通过POST 所需的所有相关数据.

当然,我可以使用在页面上有一个不可见形式的旧hack,在用户点击按钮之后填入我需要的所有数据,然后自动提交().但这看起来很麻烦 - 使用类似的语法更好$.post,而不是开始操纵html.$.post它是完美的,它实际上是重定向到页面而不是异步地发出请求(我不能只是page 1在ajaxy帖子完成后重定向到page 1需要数据显示的东西).

有没有办法用jquery做我想要的东西,或者丑陋的隐形形式是唯一的出路?

PS

我知道还有其他复杂的方法可以实现我想要的东西,例如$.post在我们当前使用的页面中使用和只是种植响应的html,但我只是想知道是否有一种直接的方式来实现这一点与jquery

Gre*_*g W 15

这让我想到了一个小jQuery函数来模仿你所描述的$ .post行为.它仍然在后台使用不可见的形式,但它的语法相对简洁明了.

$(document).ready(function(){
    $('#myButton').PostIt('post.php', {foo:'bar', abc:'def', life:42});
    $('#myOtherButton').PostIt('post.php', dataObjectFromSomewhereElse);
});

$.fn.PostIt = function(url, data){

  $(this).click(function(event){

        event.preventDefault();

        $('body').append($('<form/>', {
          id: 'jQueryPostItForm',
          method: 'POST',
          action: url
        }));

        for(var i in data){
          $('#jQueryPostItForm').append($('<input/>', {
            type: 'hidden',
            name: i,
            value: data[i]
          }));
        }

        $('#jQueryPostItForm').submit();
    });
}
Run Code Online (Sandbox Code Playgroud)

  • @Flo那不是JSON,它只是一个JavaScript对象. (2认同)

cri*_*aig 9

我将Greg W的代码改编成了一个可以在代码中调用的直接函数:

function postIt(url, data){

    $('body').append($('<form/>', {
      id: 'jQueryPostItForm',
      method: 'POST',
      action: url
    }));

    for(var i in data){
      $('#jQueryPostItForm').append($('<input/>', {
        type: 'hidden',
        name: i,
        value: data[i]
      }));
    }

    $('#jQueryPostItForm').submit();
}
Run Code Online (Sandbox Code Playgroud)


ola*_*ndo 0

我想答案是没有直接的方法。对于添加此功能的通用函数,请参阅 Greg W 的回答。