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

更新时间:2019-12-04    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

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');  
} 
</script>





调用:

javascript:void(0);" onClick="openPostWindow('noWriteSiteInfo.jsp','noWriteSiteInfo','<%=lowerOffset %>');">
   这里是调用;  
 



注意红色部分 如果没有这个,会导致页面上 这种页面丢失,这是 链接的href 和 onclick 共存问题,

请求的链接是用的 A 标签,A上同时写了href和onclick事件。对于链接 A 标签而言,当用户鼠标单击的时候,A对象被触发时会首先去执行onclick部分,然后是href。

解决方法就是:

直接把onclick事件写在href中:href="javascript:openPostWindow(。。。)"
还有一种解决方案:Test
这样是忽略了href部分,这对于通过onclick传递this,或者无法避开a对象时都有用。

本文来源:http://www.bbyears.com/jiaocheng/82207.html