Javascript: How to test JSONP on localhost

微笑、不失礼 提交于 2019-12-12 22:09:19

问题


Here is the way I test JSONP: I run XAMPP, and in folder htdocs I create a javascript folder . I create json1.json file contain some data to process.

After that, I run this html file locally, and it will call a function in "other machine" (in this case is localhost)

Here is my code in this problem :

<head>
    <script>
            function updateSales(sales) {
                alert('test jsonp');
                // real code here
                }

    </script>

    </head>
    <body>
        <h1>JSONP Example</h1>
        <script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
    </body>

But when I run, nothing happen. But if change to other real json on the internet, it will work. It means change line :

<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>

to line:

<script src="http://gumball.wickedlysmart.com/?callback=updateSales"></script>

It will work smoothly.

So, I don't know how to test JSONP by using localhost, please help me.

Thanks :)


回答1:


JSONP is generated on the server's side. The server fetches your data, encodes it as JSON and then wrap a function call around it.

So in your case you can either modify your .json file the following way:

updateSales( { /* your data */ } );

This, however, would have a hardcoded call back method, so it wont react on changes you do at retrieving it.

The other way is to write a small PHP wrapper (or use whatever else you like) and add the function around the JSON, before sending it back to the client.

<?php

  $json = file( "path/to/your/json" );

  echo $_GET['callback'], '(', implode( '', $json ), ');';

?>

(The later code is by no means for any productive use, but only for local testing!)



来源:https://stackoverflow.com/questions/11064572/javascript-how-to-test-jsonp-on-localhost

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