简体   繁体   中英

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:

<employee id = "msarapin">
    <login>msarapin</login>
    <name>Marvin I Sarapin, Ph.D.</name>
    <title>Department Head</title>
    <position>Administration</position>

Here is my jquery code:

$('#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:

<?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. You need to use .html() , and that means you need to wrap the XML object in another node, like this:

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. 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. If there's only one of each of these nodes, then there's no need for the nested .each() methods. Either way, you can just select like this:

$(xml)
    .find('employee[id$='+"<?php echo($_GET["id"]); ?>"+']')
    .find('name')
    .text("New Name");
$.post( ... );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM