Simple jQuery, PHP and JSONP example?

后端 未结 7 2271
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 16:36

I am facing the same-origin policy problem, and by researching the subject, I found that the best way for my particular project would be to use JSONP to do cross-origin requ

7条回答
  •  爱一瞬间的悲伤
    2020-11-22 17:13

    First of all you can't make a POST request using JSONP.

    What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

    Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

    This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

    The best thing to do is adding &callback=? to you url.

    At the server side you've got to make sure that your data is wrapped in this callback function.

    ie.

    echo $_GET['callback'] . '(' . $data . ')';
    

    EDIT:

    Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

    Replace Liam's line

     echo "{'fullname' : 'Jeff Hansen'}";
    

    with

     echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
    

提交回复
热议问题