简体   繁体   中英

JSONP - ajax request callback fails

I'm pushing some data from one domain to other using jsonp . I'm getting data on the 2nd server and the process works fine. But the callback is not working properly.Even after getting the data on the other server the request is showing pending status and after sometime the request fails with error net::ERR_EMPTY_RESPONSE

$.ajax({
    type: 'GET',
    url: url,
    crossDomain: true,
    data: data,
    dataType: 'jsonp',
    success: function(responseData, textStatus, jqXHR) {
      console.log('success')
    },
    error: function(xhr,status,error){
      console.log('error')
    }
});

When the request fails, I gets 'error in the console.

Update :

Headers

Request URL:http://example.com:3000/request?callback=jQuery21309164826604537666_1429167109185&firstname=sdf&lastname=sdf&_=1429167109187
Request Headers
Provisional headers are shown
Accept:*/*
Referer:http://localhost/widgets/form.html
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Query String Parameters
view source
view URL encoded
callback:jQuery21309164826604537666_1429167109185
firstname:sdf
lastname:sdf
phone:sdf
email:sdf
_:1429167109187

I think your problem is that the jQuery with jsonp is expecting some JSON back. Your response body should then look like

jQuery21309164826604537666_1429167109185({});

In PHP you can simply return a dummy function like this:

$callback = isset($_GET["callback"]) ? $_GET["callback"] : "?";
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json");
echo $callback . "({});";

For Node.js, you can just use

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Content-Type", "application/json"); 
res.jsonp({});

Ref: ExpressJS JSONP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM