Cross-site XMLHttpRequest

前端 未结 3 1248
温柔的废话
温柔的废话 2020-11-29 02:37

I want to provide a piece of Javascript code that will work on any website where it is included, but it always needs to get more data (or even modify data) on the server whe

3条回答
  •  鱼传尺愫
    2020-11-29 03:02

    Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?

    No, because the script is loaded on to a seperate domain it will not have access...

    If you trust the data source then maybe JSONP would be the better option. JSONP involves dynamically adding new SCRIPT elements to the page with the SRC set to another domain, with a callback set as a parameter in the query string. For example:

    function getJSON(URL,success){
        var ud = 'json'+(Math.random()*100).toString().replace(/\./g,'');
        window[ud]= function(o){
            success&&success(o);
        };
        document.getElementsByTagName('body')[0].appendChild((function(){
            var s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = URL.replace('callback=?','callback='+ud);
            return s;
        })());
    }
    
    getJSON('http://YOUR-DOMAIN.com/script.php?dataName=john&dataAge=99&callback=?',function(data){
        var success = data.flag === 'successful';
        if(success) {
            alert('The POST to abc.com WORKED SUCCESSFULLY');
        }
    });
    

    So, you'll need to host your own script which could use PHP/CURL to post to the abc.com domain and then will output the response in JSONP format:

    I'm not too great with PHP, but maybe something like this:

    
    

    So, your server, which you have control over, will act as a medium between the client and abc.com, you'll send the response back to the client in JSON format so it can be understood and used by the JavaScript...

提交回复
热议问题