开发者

Get xml with HTTPRequest in a page without an xml file extension

开发者 https://www.devze.com 2023-03-13 14:38 出处:网络
I am trying to use an HTTPRequest using jquerys ajax function to get the xml from a page. The function is not returning anything.My theory of why this is not working is because the page I am hitting h

I am trying to use an HTTPRequest using jquerys ajax function to get the xml from a page. The function is not returning anything. My theory of why this is not working is because the page I am hitting has the file extension ".ns" rather than ".xml" This is the FULL page source of the page I am hitting.

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

How can I get this XML from an HTTPRequest?

Some additional information that may help: When I save the webpage it saves as "command.ns.xml" (whi开发者_如何学运维ch the url only has the .ns and not the .xml) and when I hit this page in the same directory as my own file (with the .xml extension) that has the request, it works fine.

Also the domain that the file making the request is on is "www.csun.edu" and the page i'm hitting is on "remotesupport.csun.edu". Could this be a problem?

Here is the code to make the call (unfortunately I cannot provide the username and password with the url I am hitting)

$.ajax({
    url: 'https://remotesupport.csun.edu/api/command.ns?username=user&password=pass&action=get_logged_in_reps',
    type: 'GET',
    datatype: 'xml',
    success: function(xml) {
        alert(xml);
    }
});


To get round the Same Origin Policy issue, and the fact that the server you want to get the XML from doesn't support JSONP, you can use YQL.

Here's an example

You would then use this as the URL for your JSONP request:

http://query.yahooapis.com/v1/public/yql?q=select * from xml where url="http://the-xml-url.com"

So for you problem you would do something like this:

yql_url = function(source_url) {
  return "http://query.yahooapis.com/v1/public/yql?q=select * from xml where url=\"" + source_url + "\"";
};

$.ajax({
    url: yql_url('https://remotesupport.csun.edu/api/command.ns?username=user&password=pass&action=get_logged_in_reps'),
    type: 'GET',
    dataType: 'xml',
    success: function(xml) {
        console.log($(xml).find('result'));
    }
});


There are two main problems.

First, you are denied access to that XML file because of Same Origin Policy.

Second, the dataType argument must be used as that exact string.


Yes the problem is the security restriction called Same Origin Policy.

You can circumvent it using the JSONP technique (see JQuery support explained here), but that requires you to wrap the generated XML output.

Another solution is to proxy your Ajax request through the origin server (that is, www.csun.edu in your case).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号