JQuery中的$.post(url,data,fun)函数获取php后台返回的对象
网上找了很多居然都找不到,呜~最终自己悟出来了,真是令人百感交集
一、这是前台页面index.php
<?php
?>
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="utf-8">
<script src
="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script
>
<script
>
$(document
).ready(function(){
$("button").click(function(){
$
.post("zj.php",{
name1
:"safd",
url
:"sdfsfa"
},
function(data
,status
){
var v
= JSON.parse(data
);
for(var i
in v
){
alert(i
+ ":" + v
[i
]);
}
});
});
});
</script
>
</head
>
<body
>
<button
>发送一个
HTTP POST 请求页面并获取返回内容
</button
>
</body
>
</html
>
二、这是后台页面zj.php
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
(2019.1.12)新增
如果在js的ajax异步传输的post方法中传输json数组,js前台如何发送?PHP后台如何处理?
js前台页面代码,使用JSON.stringify(str)进行序列化:
function database(){
if(!confirm("导入数据库可用于课程分数统计,如果数据库中已导入本场竞赛成绩,现在导入将覆盖原本的记录,是否要继续?"))return;
$
.post("postFunction.php?action=destroy", {contest_id
: <?php echo $cid
?>}, function(){
var tb
= window
.document
.getElementById('rank');
var rows
= tb
.rows
;
try {
var total
= getTotal(rows
);
var jsonarray
= [];
for (var i
= 1; i
< rows
.length
; i
++) {
var rank
= i
;
var user
= rows
[i
].cells
[1].innerText
;
var solved
= rows
[i
].cells
[3].innerText
;
var penalty
= rows
[i
].cells
[4].innerText
;
var param
= {
contest_id
:<?php echo $cid
?>,
rank
:rank
,
user
: user
,
solved
: solved
,
penalty
:penalty
};
jsonarray
.push(param
);
}
console
.log(jsonarray
);
$
.post("postFunction.php?action=database", {jsonarray
:JSON.stringify(jsonarray
)}, function(){
alert("导入成功!");
});
} catch (e) {
console
.log(e
);
}
});
}
PHP后台台吗代码,使用json_decode将json字符串转化为PHP数组
<?php
if(isset($_GET['action']) && $_GET['action'] == 'database'){
$jsonarray = $_POST['jsonarray'];
$array = json_decode($jsonarray, true);
$len = count($array);
for($i = 0; $i < $len; $i++){
$user = $array[$i]['user'];
$rank = $array[$i]['rank'];
$solved = $array[$i]['solved'];
$penalty = $array[$i]['penalty'];
$contest_id = $array[$i]['contest_id'];
pdo_query("INSERT INTO contest_rank (contest_id, rank, user_id, solved, penalty) VALUE (?, ?, ?, ?, ?)", $contest_id, $rank, $user, $solved, $penalty);
}
}
?>