JavaScript发布请求,如表单提交 [英] JavaScript post request like a form submit

查看:114
本文介绍了JavaScript发布请求,如表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将浏览器定向到其他页面。如果我想要一个GET请求,我可能会说

I'm trying to direct a browser to a different page. If I wanted a GET request, I might say

document.location.href = 'http://example.com/q=a';

但我尝试访问的资源不会正常响应,除非我使用POST请求。如果这不是动态生成的,我可以使用HTML

But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML

<form action="http://example.com/" method="POST">
  <input type="hidden" name="q" value="a">
</form>

然后我只需从DOM提交表格。

Then I would just submit the form from the DOM.

但我真的想要JavaScript代码让我说

But really I would like JavaScript code that allows me to say

post_to_url('http://example.com/', {'q':'a'});

什么是最好的跨浏览器实现?

What's the best cross browser implementation?

编辑

对不起,我不清楚。我需要一个可以改变浏览器位置的解决方案,就像提交表单一样。如果使用 XMLHttpRequest 可以实现这一点,那么这一点并不明显。这不应该是异步的,也不应该使用XML,所以Ajax不是答案。

I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with XMLHttpRequest, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.

推荐答案

function post(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();
}

示例:

post('/contact/', {name: 'Johnny Bravo'});

编辑:由于这已经投入了很多,我猜人们将复制粘贴这么多。所以我添加了 hasOwnProperty 检查以修复任何无意的错误。

EDIT: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the hasOwnProperty check to fix any inadvertent bugs.

这篇关于JavaScript发布请求,如表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆