无法通过AJAX发送JSON

时间:2023-01-03 18:13:35

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.

我创建了一个函数来计算我在某个页面上花了多少时间以及我来自哪里。我收集所有数据并将其保存为JSON但是当我尝试通过ajax发送该JSON成功时,它会通过空警报框提醒我,这意味着没有任何内容被发送。我试图将async添加到false,因为我使用onbeforeunload函数,但这不起作用。我尝试了无数组合与AJAX设置,但没有任何工作。

HTML / JS

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 个解决方案

#1


1  

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

你的test.php正在寻找一个名为main的POST变量,但你要发送一个名为data的变量。

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

您可以从以下位置更改ajax调用的数据部分:

data: {'data': main}

to

data: {'main': main}

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

这应该使它发布变量与main作为变量名称。

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

其次,当您返回数据时,最好再次将其作为JSON返回,否则可能会稍微破坏结果。

Replace

echo $obj;

with

echo json_encode($obj);

And in the ajax replace

并在ajax替换

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.

当if语句为false时,您还应该考虑从PHP返回一些内容,无论是错误代码还是其他响应。在这种情况下不发送响应对客户端没有太大帮助,并阻碍了您的调试。

#1


1  

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

你的test.php正在寻找一个名为main的POST变量,但你要发送一个名为data的变量。

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

您可以从以下位置更改ajax调用的数据部分:

data: {'data': main}

to

data: {'main': main}

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

这应该使它发布变量与main作为变量名称。

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

其次,当您返回数据时,最好再次将其作为JSON返回,否则可能会稍微破坏结果。

Replace

echo $obj;

with

echo json_encode($obj);

And in the ajax replace

并在ajax替换

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.

当if语句为false时,您还应该考虑从PHP返回一些内容,无论是错误代码还是其他响应。在这种情况下不发送响应对客户端没有太大帮助,并阻碍了您的调试。