weixin_33716557 2017-01-10 11:28 采纳率: 0%
浏览 87

无法通过AJAX发送JSON

I made a function which counts how much time I spent on some page and where I came from. I collect all the data and save it into a JSON but when I try to send that JSON via ajax on the success it alerts me with an empty alert box, which means that nothing is being sent. I tried to add async to false because I use the onbeforeunload function but that doesn't work. I tried numberless combinations with AJAX setting but nothing is working.

HTML / JS

(function(){
var time,timeSite,endTime,seconds,testObject,retrievedObject,text;
window.onload=function(){
    time= new Date();       
}
window.onbeforeunload=function(){
    endTime = new Date();
    timeSite= time.getTime()-endTime.getTime();
    seconds =Math.abs(timeSite/1000);
    window.localStorage['seconds']=seconds;
    text = 'Visitor accessed site directly.';
    if(document.referrer == ''){
        var link = text;
    } else{
        var link = document.referrer;
    } 
     var url = window.location.href;
     var main = {
        'From': link,
        'Current was' : url,
        'Time Spent': seconds
     }
     $.ajax({
           type: "POST",
           data: {'data': main},
           url: "http://localhost:8080/projectFour/test.php", //i use this page only to check if i receive data
           contentType:'application/json',
           success:  function(data) {
                alert(data);
           }, 
           error: function(xhr, ajaxOptions, thrownError) {
        if (xhr.status == 200) {

            alert(ajaxOptions);
        }
        else {
            alert(xhr.status);
            alert(thrownError);
        }
    }
       });
}
})();

Test.php

<?php 
  if(isset($_POST['main'])) { 
    $obj = json_decode($_POST['main']); 
    //some php operation 
    echo $obj; 
   } 
?>
  • 写回答

1条回答 默认 最新

  • weixin_33726943 2017-01-10 14:29
    关注

    Your test.php is looking for a POST variable called main, but you're sending one called data.

    You can change the data part of the ajax call from:

    data: {'data': main}
    

    to

    data: {'main': main}
    

    and that should cause it to post the variable with main as the variable name.

    Secondly, when you return the data, it would be better to return it as JSON again, otherwise it might mangle the result a bit.

    Replace

    echo $obj;
    

    with

    echo json_encode($obj);
    

    And in the ajax replace

    alert(data);
    

    with

    alert(JSON.stringify(data));
    

    That will give you a view of the returned data structure as a string.

    You should also consider returning something from PHP when the if statement is false, whether that be an error code, or some other response. Sending no response in this case isn't very helpful to the client side, and has hindered your debugging.

    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助