简体   繁体   English

AJAX POST返回数据未出现

[英]AJAX POST return data not appearing

I have an AJAX call which runs on a form submit (with prevent default to stop standard submit): 我有一个在表单提交上运行的AJAX调用(阻止默认情况下停止标准提交):

var form = $(this);
$.ajax({
    type: form.attr('method'),
    url: form.attr('action'),
    data: form.serialize()
}).done(function(data) {
    $('#processingFile').hide();
    $('#downloadFile').show();

    $('#shareURL').val(data.url);
    $('#downloadFile').attr('href', data.url);
    $('#aboutFile').html('<b>File URL:</b> ' + data.url + '<br /><b>File Size:</b> ' + data.size + '<br /><b>Time Stamp:</b> ' + data.timestamp + '<br /><b>Client IP:</b> ' + data.ip);
}).fail(function() {
    $('#saveFile').hide();
    $('#error').show();
});

The file it submits to is a PHP file which is as follows: 它提交的文件是一个PHP文件,如下所示:

// VARIABLES
$fileURL = $_POST['fileURL'];
$tmpURL = substr(md5(rand()), 0, 7);
$deleteCode = md5($tmpURL);

// COOKIE
setcookie($tmpURL, $deleteCode, time()+86400);

// SAVE FILE
if($fileURL){
    file_put_contents("tmp/" . $tmpFile, file_get_contents("http://" . $fileURL));
}

// OUTPUT
$result = array(
    'url' => "tmp/" . $tmpFile,
    'size' => filesize("tmp/" . $tmpFile) * .0009765625 * .0009765625,
    'timestamp' => date('H:i:s d-m-Y'),
    'ip' => $_SERVER['REMOTE_ADDR']
);

echo json_encode($result);

When the script is run everywhere which uses data.x in the jQuery returns undefined. 当脚本在各处运行data.x在jQuery中使用data.x的脚本返回未定义。 Any idea why that happens and how to fix it? 任何想法为什么会发生以及如何解决?

data is a string containing your returned JSON text; data是包含您返回的JSON文本的字符串; it isn't an object. 它不是一个对象。

To parse the JSON object, you have a couple of options: 要解析JSON对象,您有两个选择:

  • Call JSON.parse() yourself. 自己调用JSON.parse()

  • Pass dataType: "json" to tell jQuery AJAX to parse it for you. 传递dataType: "json"告诉jQuery AJAX为您解析它。

  • Set Content-Type: application/json in the server's response so that jQuery knows to parse it for you. 在服务器的响应中设置Content-Type: application/json ,以便jQuery知道为您解析它。

Set dataType: 'json' and check! 设置dataType:'json'并检查! Look this doc and set your datType. 查看此文档并设置您的datType。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM