如何在jQuery Ajax请求中从XML请求中获取单个文本元素

时间:2013-07-12 19:07:14

标签: jquery xml forms response

我试图从Ajax jQuery请求中返回XML文本但由于某种原因我无法得到它。

这是我的HTML:

<script type="text/javascript">
function sendData()
{

    var fn = document.getElementById("first_name").value;
    var ln = document.getElementById("last_name").value;

    $.ajax({
    type: 'GET',
    url: 'scripts/contact.php',
    data: { first_name: fn, last_name: ln },
    success: function(returned){

            $(returned).find('data').each(function(){

            var $data = $(this);
            var first_name = $data.attr("first_name");

            alert("it worked: " + first_name);

            });

        }
    });
}
</script>

这是我的PHP页面进行处理(简化,只是试图让基础工作):

<?php

echo "
<?xml version='1.0' encoding='utf-8' ?>
<data>
<first_name>First</first_name>
<last_name>Last</last_name>
</data>

";

?>

感谢帮助。这让我很生气。

立即行动,谢谢。这是工作:

<script type="text/javascript">
function sendData()
{

    var fn = document.getElementById("first_name").value;
    var ln = document.getElementById("last_name").value;

    $.ajax({
    type: 'GET',
    url: 'scripts/contact.php',
    data: { first_name: fn, last_name: ln },
    success: success
    });
}

function success(success)
{
    var xml = $.parseXML(success);
    $xml = $( xml );
    $test = $xml.find('first_name');
    alert($test.text());

    $last_name = $xml.find('last_name');
    alert($last_name.text());
}
</script>

1 个答案:

答案 0 :(得分:0)

试试这个

$(returned).find('data').each(function(){
    var $data = $(this);
    var first_name = $data.find("first_name").text();

    alert("it worked: " + first_name);
});