一般認識url傳遞參數是以get方式,不過我們也可以用post傳遞,特別是在做一些接口時,非常有用,本文我們列舉了用php和Javascript實現的方法.
PHP實現方法
在做接口,post傳遞方式,數據以字符串形式傳輸,返回數據用JSON封裝,然后就開始各種測試啊.
分享最終的方法.
定義抓取函數:
- function http_post_data($url, $data_string) {
- $ch = curl_init();
- <a href="/tags.php/curl_setopt/" target="_blank">curl_setopt</a>($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array(
- 'Content-Type: application/json; charset=utf-8',
- 'Content-Length: ' . strlen($data_string))
- );
- ob_start();
- curl_exec($ch);
- $return_content = ob_get_contents();
- ob_end_clean();
- $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- return array($return_code, $return_content);
- }
然后是方法:
- $url = "路徑";
- $data = array(); //數組
- $data = json_encode($data); //轉化為字符串
- list($return_code, $return_content) = http_post_data($url, $data);
- $return_content = json_decode($return_content,1);
- var_dump($return_content); //輸出返回結果。
window.open url 參數post方式傳遞
最近在做web項目,碰到需要跨頁面傳遞參數的功能,就是那種需要把當前頁面的內容帶到新開的子窗體中,以前的做法是傳一個id過去,然后在新窗口中去讀數據庫的內容。雖然不怎么麻煩,但是如果內容么有在數據庫里保存,僅僅是處以擬稿狀態時,就不能實現了,用戶還常常認為是個bug。考慮采用get的方式傳遞,把需要的內容都序列化然后,通過url去傳,顯得很臃腫,而且get的傳遞內容長度有限制。于是就想到用post的方式傳遞,問題在于open方法不能設置請求方式,一般網頁的post都是通過form來實現的。如果僅僅模擬form的提交方式,那么open方法里那種可設置窗體屬性的參數又不能用。最后想辦法整了這么一個兩者結合的方式,將form的target設置成和open的name參數一樣的值,通過瀏覽器自動識別實現了將內容post到新窗口中。
比較有意思的是直接通過調用form的submit方法不能觸發onsubmit事件,查看了幫助文檔,必須手動的觸發,否則只能看到頁面刷新而沒有打開新窗口。代碼中只傳遞了一個參數內容,實際可傳遞多個。
具體代碼如下:
- function openPostWindow(url,name,data)
- {
- var tempForm = document.createElement("form");
- tempForm.id="tempForm1";
- tempForm.method="post";
- tempForm.action=url;
- tempForm.target=name;
- var hideInput = document.createElement("input");
- hideInput.type="hidden";
- hideInput.name= "content"
- hideInput.value= data;
- tempForm.appendChild(hideInput);
- tempForm.attachEvent("onsubmit",function(){ openWindow(name); });
- document.body.appendChild(tempForm);
- tempForm.fireEvent("onsubmit");
- tempForm.submit();
- document.body.removeChild(tempForm);
- return false;
- } //Vevb.com
- function openWindow(name)
- {
- window.open('about:blank',name,'height=400, width=400, top=0, left=0, toolbar=yes, menubar=yes, scrollbars=yes, resizable=yes,location=yes, status=yes');
- }
- </script>
調用:
- <A href="<a href="/js_a/js.html" target="_blank">javascript</a>:void(0);" onClick="openPostWindow('noWriteSiteInfo.jsp','noWriteSiteInfo','<%=lowerOffset %>');">
- 這里是調用;
- </A>
注意紅色部分 如果沒有這個,會導致頁面上<jsp:include page=""/> 這種頁面丟失,這是 鏈接的href 和 onclick 共存問題.
請求的鏈接是用的 A 標簽,A上同時寫了href和onclick事件。對于鏈接 A 標簽而言,當用戶鼠標單擊的時候,A對象被觸發時會首先去執行onclick部分,然后是href。
解決方法就是:
直接把onclick事件寫在href中:href="javascript:openPostWindow(。。。)"
還有一種解決方案:<a href="javascript:void(0)" onclick="do();return false;">Test</a>
這樣是忽略了href部分,這對于通過onclick傳遞this,或者無法避開a對象時都有用.
新聞熱點
疑難解答