Javascript 如何使用 JQuery 从远程 REST API 获取 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1989052/
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-08-22 22:16:43  来源:igfitidea点击:

How To Use JQuery to Get XML From Remote REST API?

javascriptjqueryxmlhttprequest

提问by Simon

Hi there (& Happy New Year!)

你好(和新年快乐!)

Are there some examples on how I can use JQUERY to get XML from a remote REST API and just display the XML? I just need a little assistance to get things going.

是否有一些关于如何使用 JQUERY 从远程 REST API 获取 XML 并仅显示 XML 的示例?我只需要一点帮助就能让事情顺利进行。

Request Details:

请求详情:

https://{username}:{password}@api.opsourcecloud.net/oec/0.9/myaccount 

Response Details:

回复详情:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<ns3:Account xmlns:ns2="http://oec.api.opsource.net/schemas/organization" .. >     
<ns3:userName>rdyer</ns3:userName> 
    <ns3:fullName>Joe Public</ns3:fullName> 
    <ns3:firstName>Joe</ns3:firstName> 
    <ns3:lastName>Public</ns3:lastName> 
    <ns3:emailAddress>[email protected]</ns3:emailAddress> 
    <ns3:orgId>1831c1a9-9c03-44df-a5a4-f2a4662d6bde</ns3:orgId> 
    <ns3:roles> 
        <ns3:role> 
            <ns3:name>primary administrator</ns3:name> 
        </ns3:role> 
    </ns3:roles> 
</ns3:Account> 

回答by SLaks

Use the jQuery.getmethod.

使用jQuery.get方法。

For example:

例如:

$.get(
    'https://{username}:{password}@api.opsourcecloud.net/oec/0.9/myaccount',
    function(data) { alert(data); }
);


EDIT: For security reasons, you cannot use AJAX to get data from a different domain. Therefore, you'll need to write a server-side script to get the data from the other domain, then call that using $.get.

编辑:出于安全原因,您不能使用 AJAX 从不同的域获取数据。因此,您需要编写一个服务器端脚本来从另一个域中获取数据,然后使用$.get.

回答by David Jensen

If you just want to display the results of the REST service and you don't care about format or anything, this is what you can do:

如果您只想显示 REST 服务的结果并且您不关心格式或任何其他内容,那么您可以这样做:

        <script>
        ....

        $.ajax('<your_rest_service_url>', {
            dataType:'xml',
            data:{},
            type:'GET',
            success:function(data, status, response) {
                var tmp=response.responseText; // THIS IS THE TRICK
                $('#result').text(tmp);

         ....
         </script>

        <span id="result"></span>

The trick is NOT use the "data" parameter (like you're suppose to.... and what everyone else on the internet is telling you to do). Just remember, this is quick and dirty.

诀窍是不使用“数据”参数(就像您假设的那样......以及互联网上的其他人告诉您做什么)。请记住,这又快又脏。