繁体   English   中英

PHP:对PHP的AJAX请求

[英]PHP: AJAX request to PHP

所以我在从AJAX请求中调用的PHP页面上包含文件时遇到了问题:

$(document).ready(function() {
$("#image-status").html('Processing images...');
});

function process_images(files) {
$.ajax ({
    type: "POST",
    url: "includes/imageprocessor.php",
    data: {files: JSON.stringify(files)},
    success: function(data){  
        $("#image-status").html(data);
    }
});
}

我正在imageprocessor.php上尝试这个require_once:

require_once("db_connect.php");

它也位于include目录中,并且可以正常工作:我只是在另一个页面上使用它来运行一个效果很好的插入。 但是当我尝试运行时:

function get_files($id) {
$query = $db->prepare("SELECT * FROM files INNER JOIN file_profile_join ON files.id = file_profile_join.file_id WHERE file_profile_join.profile_id = " . $id . " GROUP BY files.id");
try {
    $query->execute();
    $rows = $query->fetch();
} catch (PDOException $e) {
    die($e->getMessage());
}
}

稍后在imageprocessor.php中,它会出错:

Fatal error: Call to a member function prepare() on a non-object in /home/yogabopvolume26/theprivatesector.org/epic/includes/imageprocessor.php on line 90

就像它首先不需要db_connect(在那儿声明$ db)。 但是它也不会返回找不到db_connect.php的错误。

basename(__DIR__) 

(通过AJAX请求回显)在imageprocessor.php上返回“ include”。

我试过在require_once中使用绝对URL和根路径,但是随后它既不会出错也不会继续使用imageprocessor.php:在require_once返回之后,该文件没有回声。 我也无法从session_start获取当前会话(我可以从原始页面[profile.php]中使用print_r $ _SESSION,因此该会话处于活动状态)。 也许他们有关系吗? 我不知道怎么了。

希望您的db_connect.php是链接:

try {
    $db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

而且,如果将外部连接对象用于连接文件,则必须使用global将该对象访问到特定文件中

据我所知,您收到此错误是因为您没有在文件imageprocessor.php调用对象$db ,请尝试以下操作:

function get_files($id) {
    global $db;
    $query = $db->prepare("SELECT * FROM files INNER JOIN file_profile_join ON files.id = file_profile_join.file_id WHERE file_profile_join.profile_id = " . $id . " GROUP BY files.id");
    try {
        $query->execute();
        $rows = $query->fetch();
    } catch (PDOException $e) {
        die($e->getMessage());
    }
}

在非对象中调用成员函数someFunc()……

当您要使用任何对象的someFunc()方法时,都会发生这种类型的错误,但是不幸的是您的对象不是对象。

假设

$obj = New SomeObj();
$nextObj = $obj->someMethod(); // << Suppoes someMethod() returns a object if successfull
$nextObj->newMethod();

在此代码中,仅当$nextObj是对象时, $nextObj->newMethod()才能工作。 但是我们不能确定,因为$obj->someMethod(); 仅在成功时才返回对象,否则在不成功时返回。

防止这种情况的好方法是。

$nextObj = $obj->someMethod(); // << Suppoes someMethod() returns a object if successfull
if(is_object($nextObj)){
    $nextObj->newMethod();
} else {
    //Now you know that there is error while executing $obj->someMethod();
}

另一件事:由于您具有函数function get_files($id) 您自己可以看到$db变量未在函数范围内定义。 因此,$ db目前不包含任何内容。 在其他答案中,应使用global $db或可以将$db对象作为参数传递给函数。

暂无
暂无

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

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