當我試圖訪問PHP數組時,我無法訪問它。我運行代碼時保持沉默。在這裏我使用JavaScript通過獲取ajax的方法來獲取php。 createRequest()函數用作創建請求對象。然後getDetails()被用來協調displayDetails()和createRequest()。下面顯示了php文件。任何幫助將有所幫助,如何在JavaScript中通過ajax獲取php數組?
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
function getDetails() {
alert("getDetails");
request = createRequest();
if (request==null) {
alert("Unable to create request");
return;
}
request.open("GET","problems.php",true);
request.onreadystatechange = displayDetails;
request.send(null);
}
function displayDetails() {
if (request.readyState == 4) {
if (request.status == 200) {
detailDiv = document.getElementById("description");
var jsumset = JSON.parse(request.responseText);
detailDiv.innerHTML = jsumset["rop"];
}
}
}
<?php
include ("sumcreator.php");
$sumobj = new sumcreator();
$sumset = $sumobj->sumcreator();
echo $json_encode($sumset);
?>
你確定'JSON.parse'工作,你調試它? – PRAISER
改爲使用'XMLHttpRequest',你應該使用一些javascript框架,例如'jquery'等等。它會更加靈活並且跨瀏覽器可編輯。 –
抽象XMLHttpRequest只能*減少*靈活性。 jQuery不能再使它與跨瀏覽器兼容,那麼這段代碼已經是(因爲它處理來自old-IE的預標準XHR)。 – Quentin