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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题