Ajax xml不会成功

Ajax xml not going into success

本文关键字:成功 xml Ajax      更新时间:2023-09-26

我试图访问与其他文件在同一文件夹中的book.xml文件,一切都很完美,但ajax函数不会进入成功。[对象对象]显示错误。它是一个非常简单的xml。我通常通过php文件来实现。但这次我必须直接做。我使用dataType = "xml"。这似乎是个问题。无论如何,请帮助

html代码:

<body>
<h2>Hello there, ajax example is loading:</h2>
<div class="row container">
<button class="btn" onclick="gettingdata();">Get data from XML</button>
<hr>
<div class="data">
<table id="datatable">
<tbody>
  <tr>
    <th>Book name</th>
    <th>Author</th>
    <th>year</th>
    <th>price</th>
  </tr>
  </tbody>
</table>
</div>

</div>
</body>
js代码:
$.ajax({
            type: 'GET',
            url: 'books.xml',
            dataType: 'xml',
            success: function(result) {
                alert("into");
                $(result).find('book').each(function() {
                    $('.datatable tbody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('year').text() + '</td> ' +
                            '<td>' +    
                                $(this).find('price').text() + '</td> ' +   
                        '</tr>');
                });
            },
            error: function (textStatus, errorThrown) {
                alert(''+textStatus+errorThrown);
            },
            complete: function(){
                alert("done");
            }
        });

( ajax调用失败的原因)您的代码工作正常,只需将您的books.xml放在正确的位置。此外,xml文件中的数据应该是有效的。

和改变

 $('.datatable tbody').append

 $('#datatable tbody').append

我在我的系统上尝试了你的代码。它工作得很好。

这是xml:

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>