Cannot get CSV text via ajax request

▼魔方 西西 提交于 2019-12-11 12:08:38

问题


I have a little problem of not being abble to retrieve csv response.

There is a csv available here link to csv

I am trying to retrieve this data, however there is a problem with special characters in the reponse.

I successfuly recieve the data but then jQuery tries to decode it and through a syntax error: My request is:

$.ajax({
    url: 'http://toolserver.org/~daniel/WikiSense/Contributors.php?wikilang=en&wikifam=.wikipedia.org&page=Cloud+computing&since=&until=&grouped=on&order=-edit_count&max=1000&order=-edit_count&format=csv',
    dataType: "script",
    success: function(data){
        alert('success');
    },
    error: function(test1, test2, test3) {
        alert('error');
    }
});

The error is (pointing at % character)

SyntaxError: syntax error
1004+%28922%2F82%29,SamJohnston,2008-07-26+09%3A40,2013-03-07+18%

I also tried to set the dataType to text in order to not decode the data. In this case I get an error for the ajax request.

$.ajax({
    url: 'http://toolserver.org/~daniel/WikiSense/Contributors.php?wikilang=en&wikifam=.wikipedia.org&page=Cloud+computing&since=&until=&grouped=on&order=-edit_count&max=1000&order=-edit_count&format=csv',
    dataType: "text",
    success: function(data){
        alert('success');
    },
    error: function(test1, test2, test3) {
        alert('error');
    }
});

I tried to experiment with .ajax() parameters contentType, dataType, scriptCharset etc. It does not help.


回答1:


It seems to me that this is a cross-domain request which is not acceptable. Read here and here for more info




回答2:


dataType: "text" would be correct. It sounds like you're running into the Same Origin Policy, which prevents cross-domain calls. When you said dataType: "script", jQuery automatically converted the request into adding a script element rather than doing an actual ajax call. Adding script elements that reference scripts cross-domain isn't a violation of the SOP (which is why we can use CDNs like Google's and Microsoft's for common scripts). But you can't do that when grabbing the CSV, because the CSV isn't (of course) valid JavaScript code.

If the server you're retrieving from is under your control, and if you're using a modern browser (which in this case means any vaguely recent version of Chrome, Firefox, or Opera, or using IE9 or higher), you can implement Cross-Origin Resource Sharing, which allows cross-origin ajax calls if the server allows the source origin of the requesting document. CORS basically means responding to an HTTP OPTIONS call that asks whether it's okay to send the ajax call with appropriate headers.



来源:https://stackoverflow.com/questions/15609906/cannot-get-csv-text-via-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!