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