How to call external webservice using jquery “jsonp”?

前端 未结 5 594
北恋
北恋 2020-12-20 00:51

I had a previous question can jquery ajax call external webservice?


and some good developers answered me to use jsonp, but i don\'t know how to use it, i am tr

相关标签:
5条回答
  • 2020-12-20 01:42

    You can't issue a POST request using JSONP, only GET (because <script src="..."> GETs the resource).

    0 讨论(0)
  • 2020-12-20 01:42

    First you should add jsonp ('callback') in your web server like $_GET['callback']

    Second ,don't forget the ';' after the output scripts

    $data = '{"name" : "hello world"}';
    echo $_GET['jsoncallback'] . '(' . $data . ');';
    

    Now you can find out why the "missing ; before statement" problem occured.

    html:

    $.getJSON({"http://localhost:1096/MySite/WebService.asmx?callback=?",
            function(data){alert(data);}
            });
    
    0 讨论(0)
  • 2020-12-20 01:50

    Hezil's code worked for me, but I had to change the server code to this:

    $data = '{"name" : "hello world"}'; echo $_GET['callback'] . '(' . $data . ');';
    

    Note the "callback" instead of "jsoncallback".

    0 讨论(0)
  • 2020-12-20 01:51

    The point with JSONP is the P! P as in padding. You are padding the JSON object literal with a function call - invoking a function on the calling page taking the data object as an argument.

    I.e. if you request the webservice, send the desired callback function name in the query string

    ...service/?callback=hello
    

    Then the service should answer (using appropriate mime type):

    hello({a: 17, b: 4117});
    

    For a more in-depth explanation, see: http://www.stpe.se/2008/10/cross-site-data-retrieval-using-jsonp/

    0 讨论(0)
  • 2020-12-20 01:53

    I've had a similiar problem, unfortunately I don't have the code at hand.

    From memory:

    • Add [ScriptService] as an attribute to your Web Method
    • Also change your url to call the HelloWorld procedure.
      Something like http://localhost:1096/MySite/WebService.asmx/HelloWorld?callback

    See: What are some good examples of JQuery using JSONP talking to .net? & What is the best way to call a .net webservice using jquery?

    0 讨论(0)
提交回复
热议问题