AJAX calls from local javascript code to remote server

允我心安 提交于 2019-12-30 11:42:07

问题


Is it possible to make AJAX-calls (e.g. using jQuery.ajax() ) from local html/js file (e.g. file://home/a.html) to the remote server (e.g. http://domain:8080/api)? If yes, how to enable such XSS (e.g. in FF3)?

I suppose it's some browser's security settings, but can't find which ones.

And suppose there is an answer without any server-side changes (such as JSONP).

Thanks.

Code snippet:

function foo(){
       $.ajax({
           type: "POST",
           url: "http://localhost:8080/api",
           data: "Hello world",
           success: function (data, textStatus, XMLHttpRequest) {
               alert(data);
               alert("success!");
           },
           error: function(XMLHttpRequest, textStatus, errorThrown) {
               alert("fail");
           }
       });
   }

...
...

<button onclick="foo()">click me</button>

I'm getting "success" but empty data.


回答1:


Unfortunately, there are no other ways but use one of 2 methods: either JSONP as stated in previous answers or CORS. Both require server-side changes. JSONP is better if you need older browser's support, but CORS is obviously cleaner and likely doesn't require server-side scripts changes, modifying server configuration should be enough.

Hope this helps.




回答2:


Add callback=? at the end of your url which you passing to ajax




回答3:


JSONP is the way to go. If you are accessing a third party API, hopefully it will already support it. If it is your own API, you might have to add support for it yourself. You might find this related question helps you get some background: What is JSONP all about?



来源:https://stackoverflow.com/questions/5648590/ajax-calls-from-local-javascript-code-to-remote-server

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