Getting JSONP via jQuery

蓝咒 提交于 2019-12-05 07:58:27

The JSONP "protocol" relies on the site replying to your request with a JavaScript statement of the form,

 someFunction( someJSON )

The name of the function is supplied as an argument from your code, with the idea being that the response script, once consumed and interpreted by the browser, will result in a call to that function with a parsed blob of JSON — which is to say, a JavaScript object. The jQuery library will do some of the bookeeping work for you, even to the extent of creating the globally-scoped function to call (which will be code that just calls the callback you supply as the "success" argument).

Thus, you should check what the actual response from that server looks like. It sounds to me as if it may not be a server prepared to respond that way. You might need to make sure there's an extra parameter on your URL, of the form "callback=?".

diEcho

I don't know exactly what error you are facing, but there are some useful tips for using jsonp here

  • error: This handler is not called for cross-domain script and JSONP requests.
  • write jsonp: 'callback', jsonpCallback: 'jsonpCallback' in ajax parameters. Setting jsonp to callback and then setting jsonpCallback to jsonpCallback makes the querystring look like this:

    http://domain.com/jsonp-demo.php?callback=jsonpCallback&name=watever

  • Loads in a JSON block using JSONP. Will add an extra ?callback=? to the end of your URL to specify the callback.

Your complete script would look like this:

<script>
    $(document).ready(function(){

        $("#useJSONP").click(function(){
            $.ajax({
                url: 'http://domain.com/jsonp-demo.php',
                data: {name: 'Chad'},
                dataType: 'jsonp',
                jsonp: 'callback',
                jsonpCallback: 'jsonpCallback',
                success: function(){
                    alert("success");
                }
            });
        });

    });

    function jsonpCallback(data){
        $('#jsonpResult').text(data.message);
    }
    </script>

Example here

Looks like server returns wrong Content-type header.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!