JavaScript没有重定向帖子

时间:2014-03-09 15:50:33

标签: javascript url post attributes

我正在看这个POST,我想知道,有没有办法让这个功能正常工作,但没有重定向到另一个页面?

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

我的问题出在form.setAttribute("action", path);这一行,发送到另一个网站

3 个答案:

答案 0 :(得分:0)

您可以使用ajax发送请求。使用jQuery,它看起来像这样。

$.post( "test.php", $( "#testform" ).serialize() );

答案 1 :(得分:0)

在评论中修复后,这是答案版本。

您需要进行发送表单数据的AJAX调用,而不是使用表单。 了解AJAX的工作原理,一切都会变得清晰。基本上,它是一个异步调用(它发生在页面后面),但好的是你可以等待它的响应并根据该响应相应地修改你的页面(例如,显示一个'谢谢'消息,或者错误等...)。

还有更多内容,但这会让你开始。见这里:https://developer.mozilla.org/en/docs/AJAX

此外,网上有数以百万计的示例和教程,因此您知道自己需要做什么就不会有任何问题。

答案 2 :(得分:-1)

我认为iframe可以帮到你。试用:)