JavaScript发布请求,如表单提交

本文翻译自:JavaScript post request like a form submit

I'm trying to direct a browser to a different page. 我正在尝试将浏览器定向到其他页面。 If I wanted a GET request, I might say 如果我想要一个GET请求,我可能会说

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

But the resource I'm trying to access won't respond properly unless I use a POST request. 但是我试图访问的资源不会正常响应,除非我使用POST请求。 If this were not dynamically generated, I might use the HTML 如果这不是动态生成的,我可能会使用HTML

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

Then I would just submit the form from the DOM. 然后我只需从DOM提交表单。

But really I would like JavaScript code that allows me to say 但实际上我想要允许我说的JavaScript代码

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

What's the best cross browser implementation? 什么是最好的跨浏览器实现?

Edit 编辑

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. 如果使用XMLHttpRequest可以实现这一点,那就不明显了。 And this should not be asynchronous, nor use XML, so Ajax is not the answer. 这不应该是异步的,也不应该使用XML,所以Ajax不是答案。


#1楼

参考:https://stackoom.com/question/Yq5/JavaScript发布请求-如表单提交


#2楼

您可以使用DHTML动态添加表单,然后提交。


#3楼

You could make an AJAX call (likely using a library such as using Prototype.js or JQuery). 您可以进行AJAX调用(可能使用诸如使用Prototype.js或JQuery之类的库)。 AJAX can handle both GET and POST options. AJAX可以处理GET和POST选项。


#4楼

你可以使用像jQuery这样的库及其$ .post方法


#5楼

Three options here. 这里有三个选择。

  1. Standard JavaScript answer: Use a framework! 标准JavaScript答案:使用框架! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST. 大多数Ajax框架都会为您提供一个简单的方法来进行XMLHTTPRequest POST。

  2. Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. 自己创建XMLHTTPRequest请求,将post传递给open方法而不是get。 (More information in Using POST method in XMLHTTPRequest (Ajax) .) (有关在XMLHTTPRequest(Ajax)使用POST方法的更多信息。)

  3. Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that. 通过JavaScript,动态创建表单,添加操作,添加输入并提交。


#6楼

The Prototype library includes a Hashtable object, with a ".toQueryString()" method, which allows you to easily turn a JavaScript object/structure into a query-string style string. Prototype库包含一个Hashtable对象,带有“.toQueryString()”方法,允许您轻松地将JavaScript对象/结构转换为查询字符串样式字符串。 Since the post requires the "body" of the request to be a query-string formatted string, this allows your Ajax request to work properly as a post. 由于帖子要求请求的“主体”是查询字符串格式的字符串,这允许您的Ajax请求作为帖子正常工作。 Here's an example using Prototype: 这是使用Prototype的示例:

$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();
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章