您的位置:首页 > Web前端 > JavaScript

ajax传输json到后台

2015-07-26 00:00 495 查看
摘要: 获取用户输入的表单数据转换为json通过ajax传输到后台

前端:

<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
document.getElementById("hand").onclick = function() {
var request = new XMLHttpRequest();
request.open("POST", "../controller/post.php");
var jsonuserinfo = $('#form1').serializeObject();
var data = JSON.stringify(jsonuserinfo);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function() {
if (request.readyState===4) {
if (request.status===200) {
document.getElementById("postResult").innerHTML = request.responseText;
} else {
alert("发生错误:" + request.status);
}
}
}
}
</script>

后台:

<?php
error_reporting(0);
require_once('../model/PdoMySQL.class.php');
require_once('../model/config.php');
header("Content-Type: text/html;charset=utf-8");
if ($_SERVER["REQUEST_METHOD"] == "POST"){
create();
}
//创建笼位申请信息
function create(){
//判断信息是否填写完全
$data=file_get_contents("php://input");
...
//忽略后面代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: