【发布时间】:2021-10-07 18:18:04
【问题描述】:
代码从 php 文件请求关联数组。 有一个我正在使用的代码示例:
function cOffices() {
return $.post('../../init.php', {
getOffice: ''
}, (data) => {
}, 'json');
}
cOffices()
.done((data) => {
console.log(data);
});
那段代码没有在控制台上显示任何数据。 但是如果我更改代码并且不使用“json”数据类型,它会在字符串中显示所有数组
function cOffices() {
return $.post('../../init.php', {
getOffice: ''
}, (data) => {
}, 'json');
}
这是我的 php 文件
if (isset($_REQUEST['getOffice'])) {
$oficModel = new User();
$getO = $oficModel -> getOfficeData($config['dirLogin'], $config['dirPass']);
echo json_encode($getO);
}
顺便说一下,这些是我的脚本:
<script src="../js/jquery-3.6.0.min.js"></script>
<script type="module" src="../js/users.js"></script>
更新: 我想在另一个请求中请求数据后使用该请求。 这是一个例子:
$.post('../../init.php', {
getCreate: ''
}, (data) => {
let lOptions = '';
data.forEach((d) => {
lOptions += `<option value="${d.id_grupo}">${d.nom_grupo}</option>`;
});
let formCreate = `<div class="formCreate">
<form action="../../init.php" method="POST" id="formCreate" autocomplete="off">
<button type="button" class="closeForm"><i class="fas fa-times"></i></button>
<h2>Create User</h2>
<input required type="email" name="cMail" placeholder="Insert E-Mail"
maxlength="35" id="cMail">
<input required type="password" name="cPass" placeholder="Insert Password"
maxlength="24" id="cPass">
<input required type="text" name="cName" placeholder="Insert Name"
maxlength="40" id="cName">
<div class="selectOffice">
<select name="cOffice" id="cOffice" required>
<option value="" disabled selected>Select an Office</option>
${lOptions}
</select>
</div>
<div class="selectCreate">
<select name="cGroup" id="cGroup" required>
<option value="" disabled selected>Select a Group</option>
${lOffices}
</select>
</div>
<button type="submit" name="saveUser">Save</button>
</form>
</div>`;
$('.container1').prepend(formCreate);
$('.formCreate').fadeTo(400, 1);
},'json');
}
另一个更新 [已解决] 我发现了错误,在我的 php 中有 2 个同名的进程,所以当我进行 ajax 调用时,数据是 2 个 json 编码的字符串,而 ajax 无法解码。给您带来的不便敬请谅解
【问题讨论】:
-
您在此代码中返回了一个 Promise,而不是结果。 Done 应该从回调中获取数据。
标签: javascript php jquery ajax