欢迎您来到,李雷博客 | PHP博客        登录  |  注册

前端用$.ajax的post方法传JSON数据,后端PHP解析数据示例

更新:2021-09-23 18:55:16
人气:1951
来源:本站原创
A+

一、前端用$.ajax的post方法传JSON数据

//检测是否有网络
if (window.navigator.onLine) {
    $.ajax({
        type: "POST",
        timeout: 5000,
        // 设置超时时间
        url: "jiemu_test.php",
        contentType: "application/json",
        //如果提交的是json数据类型,则必须有此参数,表示提交的数据类型 
        //dataType: "json", //表示返回值类型,不必须           
        data: JSON.stringify({
            "shebei_id": '<?=$var_shebei_id?>'
        }),
        success: function(jsonResult) {
            console.log(jsonResult)
            //异步计算是否有可以播放的内容,有就刷新,没有的话就在指定间隔时间再检查,这样的好处防止页面跳动
            var give_strs = new Array(); //定义一数组
            give_strs = jsonResult.split("|"); //字符分割
            if (give_strs[0] == 'reload') { //指令要求强制更新
                window.top.location.href = 'index.php?shebei_id=<?=$var_shebei_id?>';
            } else if (give_strs[0] == 'have') { //有节目
                if (give_strs[1] != '<?=$var_jiemu_dh?>') { //而且节目与当前不同
                    window.top.location.href = 'index.php?shebei_id=<?=$var_shebei_id?>';
                } else {
                    $("#ajax_num").val(0) //网络能,清0
                    $("#status").html("最后通讯时间:" + give_strs[2]);
                    setTimeout("myscreen_reload()", <?=$var_xintiao ? >);
                }
            } else if (give_strs[0] == 'nohave') {
                $("#ajax_num").val(0) //网络能,清0
                $("#status").html("最后通讯时间:" + give_strs[1]);
                setTimeout("myscreen_reload()", <?=$var_xintiao ? >);
            }
        },
        // 例如以下错误:  /Not Found/error/timeout
        error: function(data) {
            console.log("Error:" + data.statusText) setTimeout("myscreen_reload()", <?=$var_xintiao ? >);
        }
    });
} else {
    var n_str = "<span style=color:red>(无网络)</span>";
    $("#status").html(n_str) setTimeout("myscreen_reload()", <?=$var_xintiao ? >);
}

PHP后端处理AJAX传过来的JSON数据

$post_val=file_get_contents('php://input');//jq ajax的json数据用此方法接收
$post_str=json_decode($post_val, true);
$var_shebei_id=$post_str['shebei_id'];// 设备ID

echo "nohave|".$z_last_time;
exit;


推荐的文章
# 发表我的评论
  /     /  
# 最近评论
$.ajax({ 
        url:"wjcl.php",  //编写处理页面
        data:{url:url},  //将路径传到处理页面
        type:"POST",  //传值方式
        dataType:"TEXT",
        success: function(data){
            window.location.href = "file_homework.php";  //刷新页面
          }
      })
    })
  Ads by Google
  联系博主
Hello,本博客系统采用PHP和MySql开发,程序开发完全是因为个人爱好,是自己纯手写PHP源代码,未采用任何PHP框架!
QQ:858353007   微信号:lileihot123
网站地图
会员服务
关于我们
QQ:858353007
 
广告服务
加我微信
移动端访问
 
 
Copyright © 2014- 2024 www.mdaima.com All Rights Reserved.
李雷博客,专注PHP经验、PHP教程及PHP源代码开源下载分享的PHP博客!   ICP备案号:京ICP备10202169号-4