【问题标题】:Upload and download variables using AJAX/PHP使用 AJAX/PHP 上传和下载变量
【发布时间】:2014-05-10 19:24:31
【问题描述】:

我在需要上传数据的页面上有一个 jQuery 脚本文件。根据上传的数据是否有值,PHP页面将返回当前时间(如果上传的值!isset()),或者一些sql数据。但是,当我上传的变量实际上有值时,它仍然返回!isset() 方法。我做错了什么吗?

AJAX

    $.ajax({
        url: 'download.php',
        type: 'REQUEST',
        datatype: 'json',
        data: ({
            last_downloaded: latestTimestamp,
            username: username
        }),
        success: function (data) {
        parsedData = $.parseJSON(data);

            if (!latestTimestamp) {
                latestTimestamp = parsedData.most_recent;
            }
        }
    });

}

如果latestTimestamp为null,(应该是第一次运行这个方法),那么最近一次运行。但是,当它第二次运行时,latestTimestamp 在我 console.log 时有一个值。

PHP

<?php

// Get variables sent
$last_chat_time = $_REQUEST['last_downloaded'];
$username = $_REQUEST['username'];

// Start echoing JSON

if (!isset($last_chat_time)) {
    // User did not send last chat time they have, assume they just joined
    // Get the most recent chat date
    $SQL     = 'SELECT current_timestamp() as "most_recent" from dual';
    $results = mysql_fetch_assoc(mysql_query($SQL));
    $last_chat_time = $results;
    echo '{"most_recent":"' . $results['most_recent'] . '"}';
} 
else{
    $SQL = 'return some tasty data'
    $result = mysql_query($SQL);

    $messages = Array();

while ( $row = mysql_fetch_assoc($result) ) {
    $messages[] = Array(
        'chat' => $row['chat'],
        'time' => $row['time_sent'],
        'username' => $row['username']
    );
}

echo json_encode($messages);

}

在 php 中,它总是返回第一个 if。但是,如果我直接访问 php 页面的 url 并附加 ?last_downloaded=somedate,它会返回正确的信息。我是在错误地执行 AJAX 吗?

【问题讨论】:

    标签: javascript php jquery ajax chat


    【解决方案1】:

    对我来说,这必须更新为 type : 'post or get',因为 php 的 $_REQUEST 可以同时处理这两种情况,因此您可以将类型更改为:

    $.ajax({
        url: 'download.php',
        type: 'post',
    

    或者这个:

    $.ajax({
        url: 'download.php',
        type: 'get',
    

    【讨论】:

    • 这解决了问题!非常感谢!
    • 很高兴这对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2022-01-22
    • 2011-09-02
    相关资源
    最近更新 更多