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

后端开发   发布日期:2023年05月15日   浏览次数:493

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

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

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

  1. $post_val=file_get_contents('php://input');//jq ajax的json数据用此方法接收
  2. $post_str=json_decode($post_val, true);
  3. $var_shebei_id=$post_str['shebei_id'];// 设备ID
  4.  
  5. echo "nohave|".$z_last_time;
  6. exit;


以上就是前端用$.ajax的post方法传JSON数据,后端PHP解析数据示例的详细内容,更多关于前端用$.ajax的post方法传JSON数据,后端PHP解析数据示例的资料请关注九品源码其它相关文章!