【问题标题】:Insert values from database to xml table and output them with ajax in html将值从数据库插入到 xml 表中,并在 html 中使用 ajax 输出它们
【发布时间】:2015-07-08 20:51:21
【问题描述】:

我有一个搜索框,用户可以在其中输入名称,它会显示"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);
                });
            });
        }
    });
});

感谢所有帮助,因为我现在真的很迷茫。

【问题讨论】:

  • 警告:这非常不安全,因为这些参数不是properly escaped。您应该绝不$_GET 数据直接放入查询中:它会创建一个巨大的SQL injection bugmysql_query 是一个过时的接口,不应使用,它已从 PHP 中删除。像PDO is not hard to learn 这样的现代替代品。像 PHP The Right Way 这样的指南解释了最佳实践。
  • @tadman 感谢您的提示。我知道 SQL 注入,一旦我开始工作,我会删除/改进我的答案。
  • 一开始就不应该出现。 PDO 使得编写查询变得非常容易而没有这些问题。像往常一样调试这样的代码时,始终保持 JavaScript 控制台打开。这是发现脚本错误的唯一方法。密切关注网络流量,尤其是 PHP 代码的响应。
  • @tadman 会的,先生!欣赏它。

标签: php mysql ajax xml


【解决方案1】:

客户端:

您忘记在您的网址中添加 searchLink

    $("#btnSearch").click(function () {
    var searchLink = "ajax-search.php";
    $.ajax({
        type: "POST",
        url: searchLink,
        data: {sSearchFor : $("#txtSearch").val() },
        cache: false,
        dataType: "json",
        success: function (xml) {
            $(xml).find('searchresults').find('result').each(function () {
                var name = $(this).find("name").text();
                alert(name);
            });
        }
    });
});

服务器端:

在您的 .PHP 文件上使用它。我已经评论了处理文件保存的行:

<?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);

if(isset($_POST['sSearchFor']))
    $sSearchFor = $_POST['sSearchFor'];
else
    $sSearchFor = "";

$sql = "SELECT * FROM customers WHERE name LIKE '%$sSearchFor%'";
$result = mysql_query($sql, $db) or die(mysql_error());

//Create SimpleXMLElement object
$xml = new SimpleXMLElement('searchresults');


//Add each column value a node of the XML object

while($row = mysql_fetch_assoc($result)) {
    $result= $xml->addChild('result');
    $result->addChild('id',$row['id']);
    $result->addChild('name',$row['name']);
    $result->addChild('username',$row['user_name']);
    $result->addChild('lastname',$row['last_name']);
    $result->addChild('email',$row['email']);
    $result->addChild('accountnumber',$row['account_number']);
}

// You can close BD now
mysql_close($db);

//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 file
//fclose($fp);

echo $xml->asXML();

?>

希望对你有帮助,祝你好运!

【讨论】:

  • 我已经编辑了我的答案。如果它不起作用,请告诉我错误/行为。此外,您应该测试是否设置了变量 $_POST['sSearchFor'](使用 isset 函数)。仅测试 .PHP 文件以查看是否正确生成了 XML。如果是这样,请测试客户端请求。
  • 如果我测试 php 文件,我会收到此错误:“第 2 行第 1 列的错误:文档末尾的额外内容”只要我添加您提供的代码就会出现。
  • 再次编辑。请改用我的文件。我没有安装 http 服务器应用程序,所以我不能完全测试 PHP,但应该这样做。 (不知道我编辑答案时你是否收到通知)
猜你喜欢
  • 2017-05-24
  • 2018-04-20
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2017-04-09
  • 2012-01-11
  • 2012-10-12
  • 1970-01-01
相关资源
最近更新 更多