【问题标题】:Implementing JSONP function [closed]实现 JSONP 函数
【发布时间】:2014-02-14 14:37:02
【问题描述】:

我正在使用 JSONP,我的目标很简单,返回的数据必须显示在我的 div 中。该代码当前不显示任何内容。我还在我的项目中集成了 jquery.jsonp.js 我的路径:

                 PRJFOLDER->WEBPages->JavaScript->query.jsonp.js

index.html 文件在路径中:

                  PRJFOLDER->WEBPages->index.html

我的代码:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script type="text/javascript" src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
        <script>
          function getData(url, data, callback) {
             $.ajax({
              url : url,
              type : 'post',
              jsonp: "callback", // Needed for jsonp
              dataType: "jsonp", // Also needed for jsonp
              timeout : timeout,
              data : data || {},
              success : function(data) {
               callback(data);
              } // Omitted failure for this example
            });
            }
        </script>

    </head>
    <body>
        <h1>Hello World!</h1>
        <script>
                var data = {};
                var url = 'http://feeds.delicious.com/v2/json/popular?callback=?'

                getData(url, {}, function(result) {
                console.log(result);
                data = result;
                });

                $('#post-result').append(JSON.stringify(data));
        </script>

       <div id='post-result'></div>
    </body>
</html>

谁能帮我显示输出

【问题讨论】:

  • jquery.jsonp.js 是什么?
  • 如果 jsonp.js 使用 jQuery,那么你需要重新排序你的脚本
  • 您的包含顺序错误。
  • 您真的不需要 JSONP 插件。您可以使用$.ajax。只需将$.jsonp({ 更改为$.ajax({,并添加"dataType": 'jsonp'。我假设这就是插件所做的一切。另外,您希望.append(data) 做什么? .append() 需要一个节点(或 jQuery 对象或 HTML 字符串),而不是对象。
  • 谢谢,我会试试这个。我期待 append 将返回结果附加到 div 容器中

标签: javascript jquery jsonp


【解决方案1】:

首先,删除 jsonp。没有必要这样做。 现在请记住,当您使用 jsonp 时,服务器将发送一个函数作为返回值,而不是一个对象。

幸运的是,jquery 支持 jsonp 并且会给出一个对象字面量作为值。 只需事先确保您的 api url 支持 jsonp。

请看下面的代码:

function getData(url, data, callback) {
 $.ajax({
  url : url,
  type : 'post',
  jsonp: "callback", // Needed for jsonp
  dataType: "jsonp", // Also needed for jsonp
  timeout : timeout,
  data : data || {},
  success : function(data) {
   callback(data);
  } // Omitted failure for this example
});

在此之后,您需要创建一个函数来接收该值:

var data = {};
var url = 'http://feeds.delicious.com/v2/json/popular?callback=yourFunction'

getData(url, {}, function(result) {
console.log(result);
data = result;
});

现在您已经获得了数据,您可以通过模板或作为原始文本轻松地将其添加到您的 html 中

原始文本:

$('#post-result').append(JSON.stringify(data));

哦,我强烈建议您将应用程序代码放在结束 body 标记之前。

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 2019-12-07
    • 2013-09-19
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多