【问题标题】:JSONP in Angularjs [duplicate]Angularjs中的JSONP [重复]
【发布时间】:2018-10-29 00:22:34
【问题描述】:

我想从我的数据库中获取数据到我的 Angluar.js。

所以我创建了一个 php 文件,用于选择我的数据。 我读到我必须使用 jsonp,否则我将无法获取数据。

数据.php

<?php 
    $db = mysqli_connect("xxx", "xxx", "xxx", "xxx");
    $select = "select * from product;";
    $result = mysqli_query($db,$select);        

    if ($result) {
        $i=0;
        $outp = "";
        while ($row = mysqli_fetch_assoc($result))
        {
            if ($outp != "") {$outp .= ",";}
            $outp .= '"preis":"'   . $row["preis"]        . '",';
            $outp .= '"name":"'. $row["name"]     . '"}';
        }
        $outp ='{"records":['.$outp.']}';

        echo($outp);
    }
 ?>

App.js

var url = "http://server/data/data.php?callback=JSON_CALLBACK"

    $http.jsonp(url)
    .success(function(data){
        console.log(data.found);
    });

现在我得到一个语法错误: “SyntaxError:意外标记:':'”

感谢您的帮助

【问题讨论】:

  • “我读到我必须使用 jsonp,否则我将无法获取数据。” — 不。如果你想跨源做 Ajax,你需要做一些事情来解决同源策略。 JSONP 是实现这一目标的肮脏黑客。我们现在有 CORS。使用 CORS。
  • 不要通过手动将字符串混合在一起来生成 JSON。 PHP 拥有 json_encode 已经很久了。
  • 现在我使用了 json_encode,看起来 SyntaxError 已经消失了。但是当我运行 js 时出现 404 错误......即使是 php 也报告了正确的数据。我可以输入我的网址,例如jsonformatter.org。它说这是一个有效的json。您在此处链接为副本的问题对我没有帮助。还有其他建议吗?
  • 404 仅表示您在遇到任何其他问题的情况下 URL 错误。
  • 但我可以访问该网址。这就是为什么我想知道,为什么它说 404...

标签: php angularjs jsonp


【解决方案1】:

不要自己构建 JSON。试试这个。主要的是,只需按照您喜欢的方式创建一个数组,然后使用json_encode()

$result = [];
while ($row = mysqli_fetch_assoc($result))
{
    $result[] = $row;
}

echo json_encode($result);

【讨论】:

  • 这暂时帮助了我。看起来 json 对象现在是正确的。但我总是收到 404 错误。看起来我无法访问数据。但是我可以在我的浏览器中打开网址,我可以看到数据。
猜你喜欢
  • 2020-02-07
  • 2017-12-16
  • 2015-04-14
  • 2017-07-30
  • 2013-09-12
  • 2015-06-15
  • 2017-12-15
  • 2015-11-18
  • 2015-06-07
相关资源
最近更新 更多