开发者

AJAX calls from local javascript code to remote server

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 开发者_JAVA百科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.


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.


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


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?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜