Is there any way to receive simple json with $.ajax jsonp?

时间:2016-04-04 18:40:23

标签: javascript jquery json ajax jsonp

How can I receive data from another domain assuming it returns simple JSON not JSONP result?

$.ajax({
    type: "post",
    url: "https://example.com",
    data : {
        key1 : "value1"
    },
    dataType: "jsonp",
    jsonpCallback: "myJsonMethod"
});

The problem is that the server returns only JSON and there is no other option. The host doesn't support CORS.

--

The answer is no way using jQuery ajax method.

To get all this stuff working the server has to wrap JSON response into some callback function.

For example assuming server side language is PHP:

...
$response = ['key' => 'value'];    
echo 'callback(' . json_encode($response) . ')';

Only in that case you will be able to receive JSON in $.ajax success callback.

If the server you request for doesn't support this feature you should search some other ways to do it.

0 个答案:

没有答案