jquery $.ajax()取xml資料的小問題解決方案

來源:互聯網
上載者:User

開始的代碼如下: 複製代碼 代碼如下:$.ajax({
type: "get",
url: "Database/App_all.xml",
dataType: "xml",
timeout: 2000,
beforeSend: function () {},
success: function (xml) {
$(xml).find("app[id='id-1']").find("auther").appendTo($("#contain"));
},
error: function () {
alert("ajax failed!");
}
});

也就是,從App_all.xml這個檔案中找到id為“id-1”的這一項,並將繼續在其子節點中找到auther標籤,並將其內容加入到id 為contain
的div中,xml中我要尋找的內容為<auther>cocept</auther>,我就是想把cocept這個欄位取出來,放入容器中

結果這段代碼在firefox中生效,在opera中也生效,但是在Safari和chrome中卻沒有效果,於是我上jQuery的官方論壇,和StackFlowover
論壇提問,後者有人回複我:
  I assure you I was using $.ajax with Chrome just five hours ago at the office, and had no such problem.
  I also imagine they use it here on SO and I have no problems here. I have no problems on jQueryUI in Chrome. I think it is your code.
大意就是斬釘截鐵的說他用起來沒有問題,是我自己的問題,我也納悶了,後面也有人給我的建議更複雜:

You should use chrome's or safari's built-in developer tools (ctrl+shift+i) to track JS errors and track actual AJAX requests.

Is your code wrapped in document.ready? Is there any erros in javascript console? Also try to output something after success callback line.
Another cause for this could be incorrect mime-type for your XML file returned by server. It should be [Content-type: text/xml].
You can check that in chrome's or safari's built-in developer tools - just look for headers tab when xml resource is selected.
If it 's actual problem, you may need to tweak web-server configuration (main config or .htaccess for apache) to return correct mime-type

畢竟是自學jquery ajax架構剛起步……就遇到這麼棘手的問題,的確麻煩……

但是,由於我一個不經意的發現,問題迎刃而解……

我用firebug查看成功後的頁面元素狀態,發現: 複製代碼 代碼如下:<div id="contain">
<auther>cocept</auther>
</div>

我恍然大悟,原來這種直接用pretendTo插入的方法會連tagname也插入進去,難怪chrome和Safari不能識別(從另一個方面來說Firefox原來強大這麼多……)  於是修改後的代碼如下: 複製代碼 代碼如下:success: function (xml) {
$("#contain").html($(xml).find("app[id='id-1']").find("auther").text());
}

先取出所需元素的text()的值,再以修改html的方法html()插入容器中,大功告成啦!測試均通過

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.