Ajax cross domain -- Jsonp

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Today in learning, want to access other server to obtain the data by using jQuery $.ajax. Then in the Console prompt

XMLHttpRequest cannot load   No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:3000' is therefore not allowed access. 


From this we can know is I want to use this 3000 port to access the 3001 but was refused

Originally used to access the local server through the Ajax, in the realization of cross domain requests through the server requests

But later found, the get method using jsonp can achieve Ajax cross domain


The following Ruby on rails as an example:
3000 port main code: (browser)

:javascript
    $(document).ready(function(){
      user_login();
    })


    function user_login(){
       $.ajax({
           type:'get',
           url:'http://0.0.0.0:3001/show_user/',
           dataType:"jsonp",
           success:success_result,
           error:error_result
     })
    }
    function success_result(username)
    {
      alert(username)
    }
    function error_result(error)
    {
      alert(error)
    }



3001 port main code (server)

def show_user
    callback=params[:callback]
    render :text =>callback+"('XiaoMing')"
end





The params[: callback] is a callback function name jQuery the default naming, the actual URL URL?callback=success_result
In fact, the success method is.
The end result is a 3000 port'XiaoMing'in pop-up prompt box


Because it is a technology.. in jQuery so it can be automatically converted into other language experiment
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Avivi at January 30, 2014 - 8:16 AM