您好,欢迎访问一九零五行业门户网

通过URL参数post传递的实现方式 PHP/Javascript

一般认识url传递参数是以get方式,不过我们也可以用post传递,特别是在做一些接口时,非常有用,本文我们列举了用php和javascript实现的方法。
php实现方法
在做接口,post传递方式,数据以字符串形式传输,返回数据用json封装。
然后就开始各种测试啊。
分享最终的方法:
定义抓取函数:
function http_post_data($url, $data_string) { $ch = curl_init(); curl_setopt($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;}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'); }
调用:
这里是调用;
注意红色部分 如果没有这个,会导致页面上 这种页面丢失,这是 链接的href 和 onclick 共存问题,
请求的链接是用的 a 标签,a上同时写了href和onclick事件。对于链接 a 标签而言,当用户鼠标单击的时候,a对象被触发时会首先去执行onclick部分,然后是href。
解决方法就是:
直接把onclick事件写在href中:href=javascript:openpostwindow(。。。)
还有一种解决方案:test
这样是忽略了href部分,这对于通过onclick传递this,或者无法避开a对象时都有用。
其它类似信息

推荐信息