使用来自服务器的 ajax 响应填充 div
Posted
技术标签:
【中文标题】使用来自服务器的 ajax 响应填充 div【英文标题】:Populate a div with ajax response from server 【发布时间】:2021-09-20 11:49:14 【问题描述】:我正在尝试用 Ajax 响应的内容填充五个 div。
我已经尝试了以下一些方法:
在标记为“POPULATION LINE”的行上,我只在第一个 div 上尝试过,如果我可以让它工作,那么其余的 div 将是相同的:
$("#time").val(result[0]);
$("#time").html(result[0]);
$("#time").innerHTML(result[0]);
$("#time").html(result['Time']);
div 的
<div class="fixed" id="time"></div>
<div class="fixed" id="operator"></div>
<div class="fixed" id="destination"></div>
<div class="fixed" id="platform"></div>
<div class="fixed" id="estimated"></div>
产生 ajax 响应的脚本:
$numberOfLine = 10;
$numberOfLRecords = 100;
$timeOffset = 60;
$timeWindow = 120;
require("OpenLDBWS.php");
$OpenLDBWS = new OpenLDBWS("TOKEN");
$response = $OpenLDBWS->GetDepartureBoard($numberOfLRecords,"GLC",0,"from",$timeOffset,$timeWindow);
header("Content-Type: text/plain");
$data = array();
if (isset($response->GetStationBoardResult->trainServices->service))
foreach($response->GetStationBoardResult->trainServices->service as $service)
$destinations = array();
foreach($service->destination->location as $location)
$destinations[] = $location->locationName;
$desticrs[] = $location->crs;
$recordtime = substr($response->GetStationBoardResult->generatedAt, 0, 16);
$origin_location = $response->GetStationBoardResult->locationName;
$origin_crs= $response->GetStationBoardResult->crs;
$time = $service->std;
$serviceID = $service->serviceID;
$operator = $service->operator;
$dest = implode($destinations);
$dest_crs = implode($desticrs);
$plat = $service->platform;
$est= $service->etd;
$datetime = substr($recordtime, 0, 16);
$recordtime = str_replace('T',' ',$recordtime);
$recordtime = date("Y-m-d H:i",strtotime($recordtime));
$data[] = array(
"Time" => $time ,
"Operator" => $operator,
"Destination" => $dest,
"Platform" => $plat,
"Estimated" => $est);
echo json_encode($data);
回应:
0: Time: "15:04", Operator: "ScotRail", Destination: "Ayr", Platform: null, Estimated: "On time"
1: Time: "15:04", Operator: "ScotRail", Destination: "Dalmuir", Platform: "17", Estimated: "On time"
2: Time: "15:04", Operator: "ScotRail", Destination: "Whifflet", Platform: "16", Estimated: "On time"
3: Time: "15:05", Operator: "ScotRail", Destination: "Neilston", Platform: null, Estimated: "On time"
4: Time: "15:06", Operator: "ScotRail", Destination: "Gourock", Platform: null, Estimated: "On time"
Ajax 调用
$(document).ready(function()
$.ajax(
url: 'test2.php',
type: 'POST',
dataType: 'JSON',
success: function(data)
var result = JSON.stringify(data);
result = JSON.parse(result);
console.log("RESULT", result);
$("#time").html(result[0]); //POPULATION LINE
$("#operator").val(result[1]);
$("#destination").val(result[2]);
$("#platform").val(result[3]);
$("#estimated").val(result[4]);
);
);
【问题讨论】:
【参考方案1】:奇怪的是,您提供了一个带有 n 个对象的数组作为响应,但您只使用其中一个。
如果您只需要第一个而不是索引0
,例如const item = data[0]
:
$.ajax(
url: 'test2.php',
type: 'POST',
dataType: 'JSON',
success: function(data)
const item = data[0];
console.log(item); // [object, Object]
$("#time").html(item.Time);
$("#operator").val(item.Operator);
$("#destination").val(item.Destination);
$("#platform").val(item.Platform);
$("#estimated").val(item.Estimated);
);
如果您有多个集合而不是使用具有 ID 的元素,并遍历您的数组,即:
// (inside the success callback)
// Use classes instead of ID
const ELs_operator = document.querySelectorAll(".Operator");
data.forEach((item, index) =>
console.log(item); // [object, Object]
ELs_operator[index].textContent = item.Operator;
);
或者如果您想动态生成元素:
// Emulating the data response
// For this DEMO ONLY!!!! you don't need this.
const data = [
Time: "15:04", Operator: "ScotRail", Destination: "Ayr", Platform: null, Estimated: "On time",
Time: "15:04", Operator: "ScotRail", Destination: "Dalmuir", Platform: "17", Estimated: "On time",
Time: "15:04", Operator: "ScotRail", Destination: "Whifflet", Platform: "16", Estimated: "On time",
Time: "15:05", Operator: "ScotRail", Destination: "Neilston", Platform: null, Estimated: "On time",
Time: "15:06", Operator: "ScotRail", Destination: "Gourock", Platform: null, Estimated: "On time",
];
// This goes inside the success callback:
const HTML_row = (item) => `
<div>$item.Time</div>
<div>$item.Operator</div>
<div>$item.Destination</div>
<div>$item.Platform || ""</div>
<div>$item.Estimated</div>
`;
const HTML = data.reduce((h, item) => h += HTML_row(item), "");
document.querySelector("#arrivals").innerHTML = HTML;
#arrivals
display: flex;
flex-flow: wrap;
#arrivals div
flex: 1 0 20%;
<div id="arrivals"></div>
【讨论】:
是不是应该先把数据解析成json? @ikiK 没有。 AJAX 已经期望dataType: 'JSON',
@RokoC.Buljan 非常感谢您的帮助。我喜欢 const 数据的想法,但数据是动态的,所以它并不总是相同的。还是我不理解您的解决方案?
@DCJones 我将const data
用作演示,因为我没有任何服务器可以从中获取该数据作为响应。您可以完全删除 const data = [.... ]
并使用 data
这显然 是您的服务器响应 - 有意义吗?我还写道:// Emulating the data response:
认为很明显您不需要它作为代码的一部分,因为您已经拥有 data
。
@RokoC.Buljan 现在我明白了。现在我有: 成功:function(data) const HTML_row = (item) => ` $item.Time $item.Operator $ item.Destination $item.Platform || "" $item.Estimated ` ; const HTML = data.reduce((h, item) => h += HTML_row(item), ""); document.querySelector("#arrivals").innerHTML = HTML;但它导致错误:test1.php:125 Uncaught TypeError: Cannot set property 'innerHTML' of null on line: document.querySelector("#arrivals").innerHTML = HTML;以上是关于使用来自服务器的 ajax 响应填充 div的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JSON 数据填充下拉列表作为 jQuery 中的 ajax 响应
Ajax 服务器响应 XMLHttpRequest | AJAX 教程