我正在尝试将浏览器指向另一个页面。如果我想要GET请求,我可以说

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

但是,除非我使用POST请求,否则我试图访问的资源将无法正确响应。如果这不是动态生成的,我可能会使用HTML

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

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

但实际上,我希望JavaScript代码能够让我说

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

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

我需要一个改变浏览器位置的解决方案,就像提交表单一样。这不应该是异步的,也不应该使用XML,因此Ajax不是答案。


当前回答

我会按照其他人的建议走Ajax路线,比如:

var xmlHttpReq = false;

var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}

self.xmlHttpReq.open("POST", "YourPageHere.asp", true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);



self.xmlHttpReq.send("?YourQueryString=Value");

其他回答

这里有三个选项。

标准JavaScript回答:使用框架!大多数Ajax框架都会抽象出一种简单的XMLHTTPRequest POST方法。自己生成XMLHTTPRequest请求,将post传递到open方法而不是get。(有关在XMLHTTPRequest(Ajax)中使用POST方法的更多信息。)通过JavaScript,动态创建表单,添加动作,添加输入,然后提交。

@Aaron回答的一个简单而快速的实现:

document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();

当然,您应该使用JavaScript框架,如Prototype或jQuery。。。

不可以。您不能像提交表单一样提交JavaScript发布请求。

您可以拥有HTML格式的表单,然后使用JavaScript提交它。(如本页多次所述)。

您可以自己创建HTML,不需要JavaScript来编写HTML。如果有人这样建议,那就太傻了。

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

您的函数将按照您想要的方式配置表单。

function postToURL(a,b,c){
    document.getElementById("ninja").action     = a;
    document.getElementById("donaldduck").name  = b;
    document.getElementById("donaldduck").value = c;
    document.getElementById("ninja").submit();
}

然后,像这样使用它。

postToURL("http://example.com/","q","a");

但我会省略函数,只做。

document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();

最后,样式决定在ccs文件中。

#ninja { 
    display: none;
}

就我个人而言,我认为表格应该用名字来称呼,但现在这并不重要。

下面是我如何使用jQuery编写它的。在Firefox和Internet Explorer中测试。

function postToUrl(url, params, newWindow) {
    var form = $('<form>');
    form.attr('action', url);
    form.attr('method', 'POST');
    if(newWindow){ form.attr('target', '_blank'); 
  }

  var addParam = function(paramName, paramValue) {
      var input = $('<input type="hidden">');
      input.attr({ 'id':     paramName,
                 'name':   paramName,
                 'value':  paramValue });
      form.append(input);
    };

    // Params is an Array.
    if(params instanceof Array){
        for(var i=0; i<params.length; i++) {
            addParam(i, params[i]);
        }
    }

    // Params is an Associative array or Object.
    if(params instanceof Object) {
        for(var key in params){
            addParam(key, params[key]);
        }
    }

    // Submit the form, then remove it from the page
    form.appendTo(document.body);
    form.submit();
    form.remove();
}

Prototype库包含一个Hashtable对象和一个“.toQueryString()”方法,它允许您轻松地将JavaScript对象/结构转换为查询字符串样式的字符串。由于post要求请求的“主体”是查询字符串格式的字符串,这允许Ajax请求作为post正常工作。以下是使用原型的示例:

$req = new Ajax.Request("http://foo.com/bar.php",{
    method: 'post',
    parameters: $H({
        name: 'Diodeus',
        question: 'JavaScript posts a request like a form request',
        ...
    }).toQueryString();
};