admin 管理员组

文章数量: 1086019

Is there a way I could process an XML file and display it

<?xml version="1.0"?>
<phonebooks>
<contacts group_name="Sample" editable="1" id="0">
<contact first_name="Extension" last_name="1000" contact_type="sip" subscribe_t$
        <numbers>
                <number dial="1620" dial_prefix="" label="Extension" primary="1$
        </numbers>
</contact>
. . . 
</phonebooks>

that's what file I need it to display, just in the text area, nothing special. I'm open to most solutions. Here is what I tried so far

var textarea = $("#xml"); 

$.ajax({
    type: "GET",
    url: "http://localhost/contacts.xml",
    cache: false,
    dataType: "xml",
    success: function(xml) {
        var xmlText = new XMLSerializer().serializeToString(xml);
        textarea.text(xmlText);
    }

});

I get no display in my textarea nor any errors in the console.

Is there a way I could process an XML file and display it

<?xml version="1.0"?>
<phonebooks>
<contacts group_name="Sample" editable="1" id="0">
<contact first_name="Extension" last_name="1000" contact_type="sip" subscribe_t$
        <numbers>
                <number dial="1620" dial_prefix="" label="Extension" primary="1$
        </numbers>
</contact>
. . . 
</phonebooks>

that's what file I need it to display, just in the text area, nothing special. I'm open to most solutions. Here is what I tried so far

var textarea = $("#xml"); 

$.ajax({
    type: "GET",
    url: "http://localhost/contacts.xml",
    cache: false,
    dataType: "xml",
    success: function(xml) {
        var xmlText = new XMLSerializer().serializeToString(xml);
        textarea.text(xmlText);
    }

});

I get no display in my textarea nor any errors in the console.

Share Improve this question edited Sep 26, 2013 at 6:26 Naveen Kumar Alone 7,6785 gold badges38 silver badges58 bronze badges asked Aug 13, 2013 at 20:57 Seth EarbySeth Earby 1593 gold badges4 silver badges12 bronze badges 10
  • You want all of it in 1 textarea? And yes there is a way.. it just depends on how you want it to be displayed – putvande Commented Aug 13, 2013 at 21:00
  • Yeah in one text area, to take all these contents and put it in an editable textarea is what I need. I would just need that function to be able to read multiple names. Contacts1.xml, Contacts2.xml etc. – Seth Earby Commented Aug 13, 2013 at 21:03
  • So what have you tried? – putvande Commented Aug 13, 2013 at 21:05
  • So really, what you want is to allow users to edit the text file, and then re-save the edited file back into the server's file system? – cssyphus Commented Aug 13, 2013 at 21:07
  • @gibberish yes, that is what I would need. I'm thinking Ajax is the only way so far. – Seth Earby Commented Aug 13, 2013 at 21:09
 |  Show 5 more ments

2 Answers 2

Reset to default 5

Here is a fully working example. Just copy paste into three files named:

whateveryouwant.php
another_php_file.php (to change name, you must also change in ajax code (2 places)
contacts.xml

How It Works:

The first ajax code block runs as soon as the DOM is ready (note: no event triggers it, it just runs. The 2nd code block is triggered by a click event). The ajax sends this POST over to the PHP file called another_php_file.php: req=load. This is a key=>value associative array: "req" is the var name, and "load" is its value.

Now, look what happens inside another_php_file.php. Upon launch, the file checks what POST variables it received. If $_POST['req'] == 'load' then it reads the file from disk and ECHOes it back out. That's how AJAX works: whatever is echoed from the specified PHP processor file is received inside that AJAX code block's success: function.

And how does the xml text get inside the textarea control? Look again at that first AJAX code block. Remember that data echoed from the PHP processor file is received inside the success function? Here's the magic:

success: function(result) {
    $('textarea').val(result);
}

result is a variable (could name it anything) containing what was echoed by the PHP file. Then we use jQuery to stick result into the textarea control.

Note that I did not specify an ID for that textarea control. This code assumes there is only one on your page. If you had more than one, then you would reference the desired textarea control by its ID:

    $('#myText').val(result);

The HTML:

<head>
        <script src="//ajax.googleapis./ajax/libs/jquery/1.9.1/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {

                $.ajax({
                    type: 'POST',
                    url: 'another_php_file.php',
                    data: 'req=load',
                    success: function(result) {
                        //alert(result);
                        $('textarea').val(result);
                    }
                });

                $('#mybutt').click(function() {
                    var stuff = $('textarea').val();
                    alert(stuff);
                    $.ajax({
                        type: 'POST',
                        url: 'another_php_file.php',
                        data: 'req=save&changes=' +stuff,
                        success: function(result) {
                            alert(result);
                            //$('textarea').val(result);
                        }
                    });
                });

            }); //END $(document).ready()

        </script>
    </head>
<html>
    <body>
        <input type="button" value="Save Changes" id="mybutt" />
        <textarea id='myText'  rows="30" cols="120" value='<?php echo $xml; ?>' />
    </body>
</html>

another_php_file.php

<?php

//This necessary to prevent AJAX from automatically ESCAPING all values (e.g. "Bob" is turned into \"Bob\" )
//See http://stackoverflow./questions/4550036/jquery-is-automatically-escaping-ajax
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}

if ($_POST['req'] == 'load') {
    $xml = file_get_contents("contacts.xml");
    echo $xml;

}else if ($_POST['req'] == 'save') {
    $d = $_POST['changes'];
    //echo $d;
    $size = file_put_contents('contacts.xml', $d);
    echo 'Wrote ' .$size. ' bytes to file. Refresh page with [Ctrl]+[F5] to see your changes.';
}

contacts.xml

<?xml version="1.0"?>
<phonebooks>
<contacts group_name="Dimple" editable="1" id="0">
<contact first_name="Extension" last_name="1000" contact_type="sip">
        <numbers>
            <number dial="1620" dial_prefix="" label="Extension" primary="1">
        </numbers>
</contact>
<contact first_name="George" last_name="Smith" contact_type="sip">
        <numbers>
            <number dial="1700" dial_prefix="" label="Extension" primary="1">
        </numbers>
</contact>
</phonebooks>

You should set dataType to "text" and contentType to "text/plain" in your ajax request because you are treating the result as a text. Your ajax request code would like below:

var textarea = $("#xml"); 

$.ajax({
    type: "GET",
    url: "http://localhost/contacts.xml",
    cache: false,
    contextType: "text/plain",
    dataType: "text",
    success: function(xml) {
        textarea.text(xml);
    }

});

本文标签: javascriptDisplay XML file to HTML Text areaStack Overflow