我有一个搜索框,用户可以在其中输入名称,并显示"firstname", "username", "lastname", "email", "accountnumber"
。到目前为止,我已经能够从数据库中获取数据,制作它的xml结构(这是学校的要求之一)。问题是如何将搜索框中的值回显到xml表中,然后将结果输出到HTML表中?
数据库代码(文件名为ajax-search.php):(我知道我使用的是mysql,我稍后会解决这个问题)
<?php
header("Content-type: text/xml");
//Create Database connection
$db = mysql_connect("127.0.0.1","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("bank",$db);
$sSearchFor = $_GET['sSearchFor'];
$sql = "SELECT * FROM customers WHERE name LIKE '%$sSearchFor%'";
$result = mysql_query($sql, $db) or die(mysql_error());
//Create SimpleXMLElement object
$xml = new SimpleXMLElement('<xml/>');
//Add each column value a node of the XML object
while($row = mysql_fetch_assoc($result)) {
$mydata = $xml->addChild('mydata');
$mydata->addChild('Id',$row['id']);
$mydata->addChild('Name',$row['name']);
$mydata->addChild('user_name',$row['user_name']);
$mydata->addChild('last_name',$row['last_name']);
$mydata->addChild('email',$row['email']);
$mydata->addChild('account_number',$row['account_number']);
}
//Create the XML file
$fp = fopen("employeeData.xml","a+");
//$fp = fopen("php://output","a+");
//Write the XML nodes
fwrite($fp,$xml->asXML()."\r\n" );
//Close the database connection
fclose($fp);
mysql_close($db);
?>
xml的代码,(文件名为xmltable.xml):
<?xml version="1.0" encoding="utf-8"?>
<searchresults>
<name>test</name>
<username>test</username>
<lastname>test</lastname>
<email>test.test@gmail.com</email>
<accountnumber>93207802685726</accountnumber>
</searchresults>
ajax的最终脚本位于索引页面上:
$("#btnSearch").click(function () {
var sSearchFor = $("#txtSearch").val();
var searchLink = "ajax-search.php?sSearchFor=" + sSearchFor;
$.ajax({
type: "GET",
url: "xmltable.xml",
cache: false,
dataType: "xml",
success: function (xml) {
$(xml).find('searchresults').each(function () {
$(this).find("name").each(function () {
var name = $(this).text();
alert(name);
});
});
}
});
});
我感谢所有的帮助,因为我现在真的迷失了。