[英]Get JSON Data from Javascript var that was created with the help of PHP DomDocument() Function
[英]Transferring DOMDocument from PHP to Javascript using function
我有一個PHP函數創建DOMDocument XML文件,我需要將DOMDocument轉換為Javascript,我已經考慮過使用
PHP中的函數返回DOMDocument,這是PHP函數
function coursexml($cc, $type){
$xmlfile = new DOMDocument();
if (@$xmlfile->load("books.xml") === false || $cc == "" || $type == "") {
header('location:/assignment/errors/500');
exit;
}
$string = "";
$xpath = new DOMXPath($xmlfile);
$nodes = $xpath->query("/bookcollection/items/item[courses/course='$cc']");
$x = 0;
foreach( $nodes as $n ) {
$id[$x] = $n->getAttribute("id");
$titles = $n->getElementsByTagName( "title" );
$title[$x] = $titles->item(0)->nodeValue;
$title[$x] = str_replace(" /", "", $title[$x]);
$title[$x] = str_replace(".", "", $title[$x]);
$isbns = $n->getElementsByTagName( "isbn" );
$isbn[$x] = $isbns->item(0)->nodeValue;
$bcs = $n->getElementsByTagName( "borrowedcount" );
$borrowedcount[$x] = $bcs->item(0)->nodeValue;
if ($string != "") $string = $string . ", ";
$string = $string . $x . "=>" . $borrowedcount[$x];
$x++;
}
if ($x == 0) header('location:/assignment/errors/501');
$my_array = eval("return array({$string});");
asort($my_array);
$coursexml = new DOMDocument('1.0', 'utf-8');
$coursexml->formatOutput = true;
$node = $coursexml->createElement('result');
$coursexml->appendChild($node);
$root = $coursexml->getElementsByTagName("result");
foreach ($root as $r) {
$node = $coursexml->createElement('course', "$cc");
$r->appendChild($node);
$node = $coursexml->createElement('books');
$r->appendChild($node);
$books = $coursexml->getElementsByTagName("books");
foreach ($books as $b) {
foreach ($my_array as $counter => $bc) {
$bnode = $coursexml->createElement('book');
$bnode = $b->appendChild($bnode);
$bnode->setAttribute('id', "$id[$counter]");
$bnode->setAttribute('title', "$title[$counter]");
$bnode->setAttribute('isbn', "$isbn[$counter]");
$bnode->setAttribute('borrowedcount', "$borrowedcount[$counter]");
}
}
}
return $coursexml;
}
所以我想做的就是在Javascript中調用函數,並返回DOMDocument。
嘗試以下
<?php include('coursexml.php'); ?>
<script>
var xml = <?php $xml = coursexml("CC140", "xmlfile");
echo json_encode($xml->saveXML()); ?>;
document.write("output" + xml);
var xmlDoc = (new DOMParser()).parseFromString(xml, 'text/xml');
</script>
您可以簡單地將此函數放入URL(例如,將其保存在獨立文件中嗎?該由您決定),然后通過AJAX從客戶端調用它。 有關進行此類調用的詳細信息,請參考如何在不使用jQuery的情況下進行AJAX調用? 。
編輯:嘗試創建一個簡單的PHP文件,其中包含並調用您具有的功能。 根據您到目前為止的描述,它可能看起來像
<?php
include("functions.php");
print coursexml($cc, $type);
假定此文件名為xml.php,當您通過瀏覽器訪問http://mydomain.com/xml.php時 ,應該會看到XML文檔(到目前為止,與Javascript無關)。
現在,在您的主文檔中,您將包含一段Javascript,它將調用此URL來加載XML。 一個示例是(假設您使用的是jQuery,有關上述鏈接的簡單Javascript函數請參見參考資料):
$.ajax({
url: "xml.php",
success: function(data){
// Data will contain you XML and can be used in Javascript here
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.