javascript 将 XML 文件显示到 HTML 文本区域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18219089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:06:17  来源:igfitidea点击:

Display XML file to HTML Text area

javascriptjqueryxmlajax

提问by Seth Earby

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

有没有办法处理 XML 文件并显示它

<?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.

我的 textarea 中没有显示,控制台中也没有任何错误。

回答by cssyphus

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

whateveryouwant.php
another_php_file.php(要更改名称,还必须更改在Ajax代码(2位)
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.

第一个 ajax 代码块在 DOM 准备好后立即运行(注意:没有事件触发它,它只是运行。第二个代码块由单击事件触发)。ajax 将此 POST 发送到名为another_php_file.php: 的 PHP 文件req=load。这是一个键=>值关联数组:“req”是变量名,“负载”是它的值。

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.

现在,看看another_php_file.php里面发生了什么。启动时,该文件会检查它收到的 POST 变量。如果$_POST['req'] == 'load'然后它从磁盘读取文件并将其回显。这就是 AJAX 的工作原理:从指定的 PHP 处理器文件回显的任何内容都在该 AJAX 代码块的success:函数内接收。

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:

以及 xml 文本如何进入 textarea 控件?再看看第一个 AJAX 代码块。还记得从 PHP 处理器文件回显的数据是在成功函数中接收的吗?这是魔法:

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

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

result是一个变量(可以命名任何东西),包含 PHP 文件所响应的内容。然后我们使用 jQuery 粘result到 textarea 控件中。

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:

请注意,我没有为该 textarea 控件指定 ID。此代码假定您的页面上只有一个。如果您有多个,那么您将通过其 ID 引用所需的 textarea 控件:

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


The HTML:

HTML:

<head>
        <script src="//ajax.googleapis.com/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

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.com/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

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

回答by meebee

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

您应该在 ajax 请求中设置dataTypeto"text"contentTypeto "text/plain",因为您将结果视为文本。您的 ajax 请求代码如下所示:

var textarea = $("#xml"); 

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

});