How to perform cross-site ajax request?

前端 未结 3 954
半阙折子戏
半阙折子戏 2021-01-22 14:42

Browsers don\'t allow cross-site AJAX calls (it\'s a security restriction). Is there any possible solution ?

EDIT

I control only the caller website

3条回答
  •  迷失自我
    2021-01-22 14:48

    Your best solution is to use JSONP calls.

     function jsonp(url, params, callback){
      var script = document.createElement("script");
      script.setAttribute("src", url+'?'+params+'&callback='+callback);
      script.setAttribute("type","text/javascript");
      document.body.appendChild(script);
     }
    
     function doit(data){
      alert(data);
     }
    
    jsonp('http://domain.com', 'foo=bar', 'doit');
    

    In the opposite side, the website you're contacting must be able to return a JSONP formatted response in order for this to work.

提交回复
热议问题