【问题标题】:JSONP PHP Array EmptyJSONP PHP 数组为空
【发布时间】:2014-06-11 00:49:23
【问题描述】:

我正在尝试使用 php 脚本通过 JSONP 从我的网页获取数据:

//connection and query above
 ...

 while($r=mysqli_fetch_array($result)){
    //Add the fetched vale to $json array
    $json[] = $r;
     // Content type
  header("Content-type: application/json");
    echo "$callback({email: 'Message from Server.php'});";

  }



  // Content type
  header("Content-type: application/json");

  //JSONP - Make it as JSONP object


echo $_GET['callback']."(".json_encode($json).")";

我的echo "$callback({email: 'Message from Server.php'});";

但我的 echo $_GET['callback']."(".json_encode($json).")";

当我在网页上调用脚本时,例如“page/callback.php”

我在浏览器中得到以下输出:

    ({email: 'Message from Server.php'});([{"0":"3","ID":"3","1":"dome","username":"dome","2":"vjvhrOWZYTq3qbrYfoE13A==","passwort":"vjvhrOWZYTq3qbrYfoE13A==","3":"mii@googlemail.com","email":"mii@googlemail.com","4":"0","active":"0","5":"hu","loc":"hu"}]

)

它包含->“[”和“]”

我的 Java 脚本是 GWT:

        JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    jsonp.requestObject(URL.encode("http://webpage/callback.php?callback=test_clbk"), new AsyncCallback<JSONreceiver>() {
        public void onFailure(Throwable throwable) {
            System.out.println(throwable.getMessage());
        }
        @SuppressWarnings("unused")
        public void onSuccess(JSONreceiver result) {
            System.out.println(result.getResult());
        }
    });

【问题讨论】:

  • 亲爱的,您是在重复两次吗?还是脚本的两个版本?个人而言,我使用Simple JSON for PHP 来伪造 JSON 响应。

标签: java php jsonp


【解决方案1】:

你仍然没有任何答案。

这是一个解决方案:

1) 删除每一个 echo / print / var_dump。

2) 用回调初始化json类

3) 使用 Simple JSON for PHP 伪造您的 JSON

4) 在文件末尾发送你的 json

结果:

<?php

include('../includes/json.php');

// Set a callback
$json = new json('callback', 'mycallback');

// Forge your data
$json->add('email', 'message sent from Server.php');

while($r=mysqli_fetch_array($result)){
  $answer[] = $r;
}

// Forge your data
$json->add('data', $answer);
$json->add('status', '200');

// Send
$json->send();

?>

【讨论】:

    猜你喜欢
    • 2016-08-29
    • 2011-11-11
    • 2012-03-12
    • 1970-01-01
    • 2013-02-09
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    相关资源
    最近更新 更多