Javascript:如何在本地主机上测试JSONP [英] Javascript: How to test JSONP on localhost

查看:116
本文介绍了Javascript:如何在本地主机上测试JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是测试JSONP的方法:运行XAMPP,并在htdocs文件夹中创建一个javascript文件夹.我创建的json1.json文件包含一些要处理的数据.

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.

之后,我在本地运行此html文件,它将在另一台计算机"(在本例中为localhost)中调用一个函数

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>

但是当我跑步时,什么也没发生.但是,如果更改为Internet上的其他真实json,它将起作用.这意味着更改行:

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>

行:

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

它将正常运行.

所以,我不知道如何使用localhost测试JSONP,请帮助我.

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

谢谢:)

推荐答案

JSONP在服务器端生成.服务器获取您的数据,将其编码为JSON,然后在其周围包装一个函数调用.

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.

因此,您可以按照以下方式修改.json文件:

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.

另一种方法是编写一个小的PHP包装程序(或使用您喜欢的任何其他方法)并在JSON周围添加功能,然后再将其发送回客户端.

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!)

这篇关于Javascript:如何在本地主机上测试JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆