crossDomain heartbeat cant parse jsonp data with j

2019-03-01 03:42发布

问题:

I embbeding my module, an asp.net project, in a "portal", the portal generate an iframe to my url, i know its a shit but i dont made it.
To avoid session in main "portal" end while user iterating with my web project the portal owner told me to start an heartbeat by javascript from my application to portal.
Everyone know keep session in this way is insecure but 'portal' there is then i havent nothing to do.
The real problem is that i cant do cross-domain requests from my application to portal because same origin policy lock it, i found a solution using jquery but it require [heartbeat listener] deal with json.
The official jsonp site here.
Someone can help me?
there is my script:

function startHeartbeat() 
{
    var interval = 9513575;
    window.setInterval(
         function () {
             $.ajax({
                 type: "GET",
                 cache: false,
                 async: true,
                 crossDomain: true,
                 url: "http://www.theportalurl.com",
                 dataType: 'JSONP',
                 complete:function(jqXHR, textStatus){                    
                     alert("Complete");
                 },
                 success:function(json){                    
                     alert("Success");
                 },
                 error:function(jqXHR, textStatus, errorThrown){
                     alert("Error:" + textStatus + ", detail:" + errorThrown);
                 },
            });

         }
     , interval
     );
}

after @rook give me help i reach this:

function startHeartbeat(pgn) 
{
    $("body").append("<img id='heartbeat' style='width:1px; height:1px' name='heartbeat' src='http://www."+Math.random()+".org'/>");
    var interval = 350000;
    window.setInterval(
         function () {
            var rnd = Math.random();
            var url = "https://www.theportal.com/refreshsession.aspx?pgn="+pgn+"&rndv="+rnd;
            $("#heartbeat").attr("src", url);
         }
     , interval
     );
}

回答1:

What you are trying to do is a clear violation of the same origin policy for JavaScript. A good solution is that the portal owner can set this http header element for the page (and only the page) that you want to fetch with an XHR.

Access-Control-Allow-Origin: http://foo.example

source: http access control