首页 > 解决方案 > 带有部分页面的 Ajax

问题描述

我有部分selectProduct.php

`<?php
$data = $query->getProductType();
var_dump($data);
$objectMap = new ObjectMap($data);
$productTypeArray = $objectMap->dataToProductType();
?>

<select name="productType" id="productType" onchange="changeAttributeForm(this)">
    <option value="0">--Select product--</option>
    <?php
    foreach ($productTypeArray as $productType) {
    ?>
        <option value="<?= $productType->getProductID() ?>" id="<?= $productType->getProductTypeName() ?>">
            <?php echo $productType->getProductTypeName() ?>
        </option>

    <?php

    } ?>
</select>` 

和第二部分attributeForm.php

  <?php
echo $productTypeArray[0];
?>

我在另一个页面中使用这两个部分form.php

<div>
<form id="#product_form">
    <label for="sku">SKU: </label>
    <input type="text" name="sku" id="sku"><br>
    <label for="name">Name: </label>
    <input type="text" name="name" id="name"><br>
    <label for="price">Price: </label>
    <input type="text" name="price" id="price"><br>
    <label for="productType">Type switcher</label>
    <?php include "partial/selectProduct.php";
    ?>
    <div id="attribute"><?php
                        include "partial/attributeForm.php"; ?> </div>

</form>

当我在form.php没有 ajax 的情况下使用这 2 个部分时,它工作得很好。但是当我使用 ajax 时:

`window.onload = function()
{
    loadAttributes(0);
}

function loadAttributes(productTypeId)
{
    var xhr =  new XMLHttpRequest();
    xhr.onreadystatechange= function()
    {
        if(this.status==200 && this.readyState==4)
        {
           document.getElementById("attribute").innerHTML = this.responseText; 
           
        }

    }

    xhr.open("GET","partial/attributeForm.php?productTypeId="+productTypeId);
    xhr.send();

}

function changeAttributeForm(e)
{
    loadAttributes(e.value);
}
`

它给了我错误Undefied variable productTypeArray in attributeForm.php。通过 var_dump($productTypeArray)我注意到,当我重新加载页面时,$productTypeArray实际上存在 0.03 秒然后它就消失了。有谁知道为什么?

编辑:在我阅读评论后,我尝试直接在我的ajax文件中创建这个丢失的对象:

 <?php
include "database/DBConnection.php";
include "database/Query.php";
include "classes/ProductType.php";
include "classes/ObjectMap.php";
$connection = new DbConnection();
$query = new Query($connection->getConnection());
$data = $query->getProductType();
var_dump($data);
$objectMap = new ObjectMap($data);
$productTypeArray = $objectMap->dataToProductType();
var_dump($productTypeArray)?>

但是对于每一include行代码,我都会收到 2 个警告:

Warning: include(database/DBConnection.php): failed to open stream: No such file or directory in C:\wamp64\www\partial\attributeForm.php on line 2

Warning: include(): Failed opening 'database/DBConnection.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp64\www\partial\attributeForm.php on line 2

标签: javascriptphpajax

解决方案


当您使用包含时,它会将该文件包含在包含它的文件的中间。

当您通过 AJAX 加载 PHP 文件时,它只加载该文件,因为您只是直接打开它。它没有在另一个文件中设置的变量的上下文。


推荐阅读