php直接输出post/get前端表单&json异步提交
更新:如需要使用php进行服务器后端直接提交表单的,请移步:
最近项目中有用到登录第三方web平台集成,里面有个小需求是可以在内部服务器上直接post/get提交相关参数到第三方服务器进行web登录。故用php做了一个简单的表单生成函数,post及get提交使用常规html表单方式提交,提交后会跳转到目标url地址。但是提交contentType:'application/json'头数据只能使用ajax异步提交,且只能获取到返回值,不能提交后直接跳转到目标地址,这种提交方式一般前后端分离服务器用的比较多一点。
<?php
$url='post.php';
$parms=array("username"=>"admin","password"=>"123456");
$model='post';
$usejson =0;//为1时 只能调用ajax提交并获取返回值,为0时使用普通html表单提交
createForm($url,$parms,$model,$usejson);
function createForm($url,$parms,$model,$usejson=0){
echo '<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>';
echo '<form action="'.$url.'" name="form1" id="form1" method="'.$model.'" >';
foreach($parms as $key =>$value){
echo '<br>'.$key.'<input type="text" name="'.$key.'" value="'.$value.'">';
}
echo '<br><input type="hidden" id="model" value="'.$usejson.'">';
echo '<br><input type="button" onclick="sub();" value="登录系统">';
echo '</form>';
echo '<script>function sub(){
var mo = document.getElementById(\'model\').value;
if(mo != 1){
document.form1.submit();
}else{
//读取表单数据并数组化---最终转换为json字符串
var formArray = $("#form1").serializeArray();
var dataArray = {};
$.each(formArray,function(){
if(dataArray[this.name]){
if(!dataArray[this.name].push){
dataArray[this.name] = [dataArray[this.name]];
}
dataArray[this.name].push(this.value || \'\');
}else{
dataArray[this.name] = this.value || \'\';
}
});
var data = JSON.stringify(dataArray);//转换成string数据,以便后台接收
////json字符串转换结束,用于下面ajax提交数据
alert(data);
$.ajax({
type: \''.$model.'\',
contentType:\'application/json\',
url: \''.$url.'\',
data: data,
success: function(data) {
alert(JSON.stringify(data));
console.log(data);
if(data.hasOwnProperty("url")){
console.log(data["url"]);
window.location.href= data["url"];//json中如有url键则跳转至该url
}else{
alert(\'返回数据无url地址\');
}
},
error:function(){ alert(\'发生错误\');}
});
}
}
// sub();
</script>';
}
?>
上述代码中有用到将form表单直接格式化为json数据的操作方法。代码提取后可封装为js函数,此处仅单独截取实现代码。
//读取表单数据并数组化---最终转换为json字符串
var formArray = $("#form1").serializeArray();
var dataArray = {};
$.each(formArray,function(){
if(dataArray[this.name]){
if(!dataArray[this.name].push){
dataArray[this.name] = [dataArray[this.name]];
}
dataArray[this.name].push(this.value || \'\');
}else{
dataArray[this.name] = this.value || \'\';
}
});
var data = JSON.stringify(dataArray);//转换成string数据,以便后台接收
//json字符串转换结束,用于下面ajax提交
基于互联网精神,在注明出处的前提下本站文章可自由转载!
本文链接:https://ranjuan.cn/php-create-postget-form/
赞赏
微信赞赏
支付宝赞赏
发表评论