AJAX cross domain call

前端 未结 11 1089
温柔的废话
温柔的废话 2020-11-22 03:43

I know about AJAX cross-domain policy. So I can\'t just call \"http://www.google.com\" over a ajax HTTP request and display the results somewhere on my site.

I tried

11条回答
  •  失恋的感觉
    2020-11-22 03:59

    Here is an easy way of how you can do it, without having to use anything fancy, or even JSON.

    First, create a server side script to handle your requests. Something like http://www.example.com/path/handler.php

    You will call it with parameters, like this: .../handler.php?param1=12345¶m2=67890

    Inside it, after processing the recieved data, output:

    document.serverResponse('..all the data, in any format that suits you..');
    // Any code could be used instead, because you dont have to encode this data
    // All your output will simply be executed as normal javascript
    

    Now, in the client side script, use the following:

    document.serverResponse = function(param){ console.log(param) }
    
    var script = document.createElement('script');
    script.src='http://www.example.com/path/handler.php?param1=12345¶m2=67890';
    document.head.appendChild(script);
    

    The only limit of this approach, is the max length of parameters that you can send to the server. But, you can always send multiple requests.

提交回复
热议问题