[英]I am trying to change the text in a node in an xml document with jquery and php
I have an xml file that begins like so: 我有一个像这样开始的xml文件:
<employee id = "msarapin">
<login>msarapin</login>
<name>Marvin I Sarapin, Ph.D.</name>
<title>Department Head</title>
<position>Administration</position>
I want to change the text inside the "name" node with jquery on click of a submit button. 我想在单击提交按钮时使用jquery更改“名称”节点内的文本。
Here is my jquery code: 这是我的jQuery代码:
$('#submitUpdate').click(function(){
$.ajax({
type: "GET",
url: "db.xml",
dataType: "xml",
success: function(xml)
{
$(xml).find('employee[id$='+"<?php echo($_GET["id"]); ?>"+']').each(function(){
$(this).find('name').each(function(){
$(this).text("New Name");
$.post('saveXml.php', { xml: $(xml)}, function(data){alert("Data Loaded: " + data);});
});
});
}
});
});
Here is my saveXml.php code: 这是我的saveXml.php代码:
<?php
$xml = $_POST['xml'];
$file = fopen("db.xml","w");
fwrite($file, $xml);
fclose($file);
echo "ok";?>
I keep getting this error: 我不断收到此错误:
Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js :: <TOP_LEVEL> :: line 18" data: no]
There are a couple of issues here, but I'm betting that the one that's tripping you up is 这里有几个问题,但我敢打赌,绊倒你的是
$.post('saveXml.php', { xml: $(xml) } ... );
It looks like you're expecting $(xml)
to echo the XML as a string, but in fact it's a jQuery object, and your error is probably due to the fact that jQuery objects aren't serializable. 看起来您期望$(xml)
以字符串形式回显XML,但实际上它是一个jQuery对象,并且您的错误可能是由于jQuery对象不可序列化。 You need to use .html()
, and that means you need to wrap the XML object in another node, like this: 您需要使用.html()
,这意味着您需要将XML对象包装在另一个节点中,如下所示:
var xmlString = $('<div/>').append(xml).html();
$.post('saveXml.php', { xml: xmlString } ... );
The other problem, which is more a style question than an actual error, is your .each()
loops. 另一个问题是.each()
循环,这是一个样式问题,而不是实际错误。 If you have multiple <employee id="this_id">
nodes, or if that node has multiple <name>
nodes, then you're calling $.post()
more often than you need to. 如果您有多个<employee id="this_id">
节点,或者该节点具有多个<name>
节点,则调用$.post()
次数将比您需要的多。 If there's only one of each of these nodes, then there's no need for the nested .each()
methods. 如果每个节点中只有一个,则不需要嵌套的.each()
方法。 Either way, you can just select like this: 无论哪种方式,您都可以像这样选择:
$(xml)
.find('employee[id$='+"<?php echo($_GET["id"]); ?>"+']')
.find('name')
.text("New Name");
$.post( ... );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.