我正试图通过XML获取一个人的名字。我正在使用jQuery获取并将名称应用于html元素。我之前试过得到人名,但它没有成功应用。是哪里有什么问题吗?我的函数语法是免费的,但我无法理解为什么它不能工作。
$.ajax({
url: 'http://support.example.com/support/api.asp?token=e6k05nbssjkjqo3qk7rd4rvr01hvlv&cmd=viewPerson',
datatype: 'xml',
success: function(data) {
$(data).find('sFullName').each(function() {
var sf = $(this).find('text').text();
$('span#username').append(
$('<a />', {
text: sf
})
);
});
},
error: function() {
console.log();
}
});
For each <sFullName>
element you are finding all the <text>
elements.
The data you are requesting looks, in part, like this:
<sFullName><![CDATA[Rajat Sharma]]></sFullName>
The element doesn't have any <text>
elements as its descendants.
You simply want:
var sf = $(this).text();
var data = $.parseXML("<?xml version=\"1.0\" encoding=\"UTF-8\"?><response><person><ixPerson>400</ixPerson><sFullName><![CDATA[Rajat Sharma]]></sFullName><sEmail><![CDATA[rajat@jonar.com]]></sEmail><sPhone></sPhone><fAdministrator>true</fAdministrator><fCommunity>false</fCommunity><fVirtual>false</fVirtual><fDeleted>false</fDeleted><fNotify>true</fNotify><sHomepage></sHomepage><sLocale><![CDATA[en-ca]]></sLocale><sLanguage><![CDATA[en-us]]></sLanguage><sTimeZoneKey><![CDATA[Eastern Standard Time]]></sTimeZoneKey><sSnippetKey><![CDATA[`]]></sSnippetKey><ixBugWorkingOn>0</ixBugWorkingOn><nType>1</nType></person></response>");
$(data).find('sFullName').each(function () {
var sf = $(this).text();
$('span#username').append(
$('<a />', {
text: sf
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="username"></span>
</div>