簡體   English   中英

將PHP Class對象傳遞給Javascript並在Javascript函數中訪問其屬性

[英]Passing a PHP Class object to Javascript and accessing its properties in Javascript function

我在訪問我創建的Javascript函數中的object屬性時遇到問題。 該對象最初是一個PHP object ,我使用json_encode()編碼為JSON

我有1個PHP文件和1個外部 JS文件。

在我的PHP文件中,我有ff:

<?php
    $announcementDaoImpl = new AnnouncementDaoImpl($pdo);
    $announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
    foreach($announcementList as $key => $value): ?>
        <tr>
        <td><?php echo $value->getId(); ?></td>
        <td><?php echo $value->getTitle(); ?></td>
        <td><?php echo $value->getDateAdded(); ?></td>
        <?php echo json_encode($value); ?> 
        <td>
        <a href="#" onclick="showEditModal('modalBox',<?php echo json_encode($value); ?>)">Edit</a>
        </td>
        </tr>
    <?php endforeach; ?>

我可以通過使用<td>上的get()方法來獲取和顯示值。 但是,當我通過json_encode($value)其編碼為JSON ,我什么都沒得到。

<?php echo json_encode($value); ?> 

echoe s {} {} {} {} {} {} {} {} {} {} {} {} {}這似乎是空對象。

我的目標是能夠將$value php對象傳遞給javascript方法showEditModal()然后訪問方法塊中的對象屬性。 object.propertyname這樣的東西

下面是javascript方法showEditModal()實現。

function showEditModal(modalDivId,object){
    alert(object.title); //returns undefined

    var modalBox = document.getElementById(modalDivId);
    var modalContentValues = document.getElementById("modalContentValues");
    modalBox.style.display = "block";
    var node = document.createElement("p");
    var text = document.createTextNode(object); //shows [object Object]
    node.style.display = "inline";
    node.appendChild(text);
    modalContentValues.appendChild(node);
}

---編輯---

這是類定義。

class Announcement {
    private $id;
    private $title;
    private $content;
    private $dateAdded;


    public function getContent()
    {
        return $this->content;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }

    public function getDateAdded()
    {
        return $this->dateAdded;
    }

    public function setDateAdded($dateAdded)
    {
        $this->dateAdded = $dateAdded;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }
} 

- 編輯結束 -

這是我的瀏覽器上顯示的內容。

在此輸入圖像描述

我已經在javascript方法中添加了一些注釋以獲取更多詳細信息。

我很感激任何幫助。

謝謝。

您可以實現JsonSerializable接口來定義在序列化對象時要使其可見的屬性; 例如:

<?php 

class User implements \JsonSerializable
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function jsonSerialize()
    {
        return [
            'name' => $this->name,
        ];
    }
}

echo json_encode(new User('Bob')); // {"name":"Bob"} 

這是以透明和隱式方式處理PHP中的對象序列化的慣用方法,它允許您為對象的json表示定義首選形狀/格式,並將其封裝在其類定義中。

在序列化嵌套對象結構時非常方便,例如,當您使用值對象時 - 這是一個(人為的)示例:

class Latitude implements \JsonSerializable
{
    private $degree;

    public function __construct(float $degree)
    {
        // validation etc.
        $this->degree = $degree;
    }

    public function jsonSerialize(): float
    {
        return $this->degree;
    }
}

class Longitude implements \JsonSerializable
{
    private $degree;

    public function __construct(float $degree)
    {
        // validation etc.
        $this->degree = $degree;
    }

    public function jsonSerialize(): float
    {
        return $this->degree;
    }
}

class Coordinate implements \JsonSerializable
{
    public function __construct(Latitude $latitude, Longitude $longitude)
    {
        $this->latitude = $latitude;
        $this->longitude = $longitude;
    }

    public function jsonSerialize(): array
    {
        return [
          'latlng' => [$this->latitude, $this->longitude],
        ];
    }
}

$coordinate = new Coordinate(new Latitude(0), new Longitude(0));

echo json_encode($coordinate); // {"latlng":[0,0]} 

示例: https//repl.it/repls/RelievedLightcyanFolders

我冒昧這是因為json_encode()掃描對象的公共屬性並將其放入結果中,但在代碼中總是使用getter函數。 在不知道$announcementList對象的類定義的情況下很難分辨。 試試這個:

<?php echo json_encode([
    'id' => $value->getId(),
    'title' => $value->getTitle(),
    'dateAdded' => $value->getDateAdded(),
]); ?>

如您的PHP代碼所示,您可以通過方法訪問對象屬性。 聽起來這些屬性是私有的。 這就是為什么當你試圖對對象進行編碼時,結果是一個空對象。

你能做什么:

class MyObject
{
    private $attribute1;
    private $attribute2;

    public function getAttribute1()
    {
        return $this->attribute1;
    }

    public function getAttribute2()
    {
        return $this->attribute2;
    }

    public function toArray()
    {
        return [
            'attribute1' => $this->attribute1,
            'attribute2' => $this->attribute2,
        ];
    }

    public function toJson()
    {
        return json_encode($this->toArray());
    }
}

現在在php文件中你可以使用它:

<?php
    $announcementDaoImpl = new AnnouncementDaoImpl($pdo);
    $announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
    foreach($announcementList as $key => $value): ?>
        <tr>
        <td><?php echo $value->getAttribute1(); ?></td>
        <td><?php echo $value->getAttribute2(); ?></td>
        <td>
        <a href="#" onclick="showEditModal('modalBox',<?php echo $value->toJson() ?>)">Edit</a>
        </td>
        </tr>
    <?php endforeach; ?>

使用這個簡單的代碼可以很好地證明這個問題:

class Foo {
    private $a = 0;
    protected $b = 1;
    public $c = 2;
}
echo json_encode(new Foo);
// Outputs {"c":2}

給定一個標准對象, json_encode將只序列化該對象的公共屬性。 如果您嘗試序列化的對象使用私有或受保護的屬性,那么JSON編碼器將無法看到這些屬性。 如果這是所有對象都有,那么你將得到一個空的JSON對象,就像你的情況一樣。

如果可以更改有問題的類,則可以實現JsonSerializable接口以自定義要序列化的屬性。 如果你不能,你將需要構建自己的表示,以使用公共getter方法傳遞給JavaScript,例如

echo json_encode([
      'id' => $value->getId(),
      'title' => $value->getTitle(),
      'dateAdded' => $value->getDateAdded()
]);

您正在嘗試編碼包含公共方法但沒有公共屬性的對象 json_encode將僅編碼公共屬性

您可以創建一個具有真實公共屬性的對象,然后將其序列化:

<?php
    $announcementDaoImpl = new AnnouncementDaoImpl($pdo);
    $announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
    foreach($announcementList as $key => $value): ?>
        <tr>
        <td><?php echo $value->getId(); ?></td>
        <td><?php echo $value->getTitle(); ?></td>
        <td><?php echo $value->getDateAdded(); ?></td>
        <?php 
             $obj = new stdClass(); 
             $obj->Id = $value->getId();
             $obj->Title= $value->getTitle();
             $obj->DateAdded= $value->getDateAdded();
             var_dump($value);  // just for debugging
             var_dump($obj);    // just for debugging
             echo json_encode($obj); 
        ?> 
        <td>
        <a href="#" onclick="showEditModal('modalBox',<?php echo json_encode($obj); ?>)">Edit</a>
        </td>
        </tr>
    <?php endforeach; ?>

喜歡喜歡

<a href="#" onclick="showEditModal('modalBox','<?php echo json_encode($value); ?>')">Edit</a>

在你的功能里面

    function showEditModal(modalDivId,object){
        object = JSON.parse(object) // convert json string to json object
        alert(object.title); //returns undefined

        var modalBox = document.getElementById(modalDivId);
        var modalContentValues = document.getElementById("modalContentValues");
        modalBox.style.display = "block";
        var node = document.createElement("p");
        var text = document.createTextNode(object); //shows [object Object]
        node.style.display = "inline";
        node.appendChild(text);
        modalContentValues.appendChild(node);
    }

(第二,備選答案)您正在嘗試編碼包含公共方法但沒有公共屬性的對象。 json_encode將僅編碼public properties

一種不同的,優雅而簡單的方法是使用Reflection創建一個新對象,其公共屬性 “反映”您的原始對象是私有的:

   <?php
   $announcementDaoImpl = new AnnouncementDaoImpl($pdo);
   $announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent(); 
   foreach($announcementList as $key => $value): ?>
        <tr>
        <td><?php echo $value->getId(); ?></td>
        <td><?php echo $value->getTitle(); ?></td>
        <td><?php echo $value->getDateAdded(); ?></td>
        <?php
             // gets all PRIVATE properties of $value and stores them to $obj 
             $reflect = new ReflectionClass($value);
             $obj = $reflect->getProperties(ReflectionProperty::IS_PRIVATE);

             echo json_encode($obj); 
        ?> 
        <td>
        <a href="#" onclick="showEditModal('modalBox',<?php echo json_encode($obj); ?>)">Edit</a>
        </td>
        </tr>
    <?php endforeach; ?>

暫無
暫無

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

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