簡體   English   中英

將一個PHP對象從ajax文件返回到我的javascript代碼

[英]returning a PHP object from an ajax file to my javascript code

所以當涉及到javascript和php時,我仍然是一個新手。 我有這個問題:

從javascript,我使用條形碼閱讀器掃描包的條形碼。 我使用ajax將它發送到一個PHP文件,它構建一個對象,並需要將它返回到我的javascript代碼。

我這樣做:

function LoadPackage(ScannedCode) {
    var res;

    console.time("Load package " + ScannedCode);
    $.ajax({
        type: "POST",
        url: "ajax/3gmodule_inventory_ajax/getPackage.php",
        data: "packageSerial=" + ScannedCode,
        cache: false,
        async: false //inline operation, cannot keep processing during the execution of the AJAX
    }).success(function(result) {
        res = $.parseJSON(result);
    });

    console.timeEnd("Load package " + ScannedCode);

    return res;
}

php文件:

    <?php
        include_once "../../init.php";

        $packageSerial = $_POST["packageSerial"];

        $package = tbProductPackage::getInstanceByPackageSerial($packageSerial, $db);
        return json_encode($package);
// edit: first part of the problem was here, I was supposed to ECHO here. not RETURN.
    ?> 

我100%確定我的對象是否正確構建。 我確實做了我的$ package對象的var_dump,一切都很好。 然而,當試圖將它恢復到javascript時,我嘗試了一堆不同的東西,沒有任何作用。

$ .parseJSON(結果); 聲明似乎給了我這個錯誤:

Uncaught SyntaxError: Unexpected end of JSON input

我也嘗試使用serialize(),但是我收到一條錯誤消息:

Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances'

基本上,我的數據庫在我的對象中,我猜我無法序列化它...

我在這做錯了什么?

謝謝

getPackage.php頁面中:

echo json_encode($package);

不要使用return

在Jquery應該是:

data: {packageSerial:ScannedCode},

成功后不需要$.parseJSON(因為getPackage.php已經檢索了json encode

所以,應該是:

}).success(function(result) {
    res = result
});

還要在data: {packageSerial:ScannedCode},之后添加dataType: 'json', data: {packageSerial:ScannedCode},

所以,最終修正代碼是:

Jquery:

function LoadPackage(ScannedCode) {
    var res;

    console.time("Load package " + ScannedCode);

    $.ajax({
        context: this,
        type: "POST",
        url: "ajax/3gmodule_inventory_ajax/getPackage.php",
        data: {packageSerial:ScannedCode},
        dataType: 'json',
    }).success(function(result) {
        res = result;
    });

    console.timeEnd("Load package " + ScannedCode);

    return res;
}

PHP:

<?php
    include_once "../../init.php";

    $packageSerial = $_POST["packageSerial"];

    $package = tbProductPackage::getInstanceByPackageSerial($packageSerial, $db);
    echo json_encode($package);
?>

Ajax期望請求體內有JSON。

使用

die(json_encode($SOME_ARRAY_OR_OBJECT));

不是"return" json_encode($SOME_ARRAY_OR_OBJECT)

我不知道您的數據庫是如何完成的,但作為第一步,您可以進行SELECT查詢並將其作為數組獲取。 然后,json_encode可以正常工作。 有點像:

$vec = array();
$query="SELECT * From YourTable
                    WHERE 1";

$result= mysql_query($query) or die(mysql_error() . $query)

while ($r=mysql_fetch_array($result)) {
   $vec [] = $r;
}

$toreturn=json_encode($vec );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM