dongpi0658 2015-10-08 18:37
浏览 104

未定义的JSONP跨域

I have an API based on Php Slim Framework and want to generate JSONP for my website. When I call the website on: 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK'. It returns a blank page with JSON CALLBACK() write on it. When logged to the console it is undefined.

API's index.php:

<?php
require 'vendor/autoload.php';

$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->run();

function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;mysql:charset=utf8mb4", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $dbh;
}

function getUsers() {
$sql = "select * FROM manga";
try {
    $db = getConnection();
    $stmt = $db->query($sql);
    $users = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo $_GET['callback'] . '('.json_encode($users).')';
}
catch(PDOException $e) {
    echo $_GET['callback'] . '('.json_encode($e->getMessage()).')';
}
}

Javascript:

.factory('MY', function($http){
var fax= {};
var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
fax.isimler = $http.jsonp(url);
return fax;
})

.controller('indexCtrl', function($scope, MY) {
 MY.isimler.success(function(alHemen){
      $scope.mangas = alHemen;
 });  
})

enter image description here

  • 写回答

1条回答 默认 最新

  • dongli2000 2015-10-08 18:41
    关注

    Don't serve it as application/json. Serve it as application/javascript. JSONP needs to be executed.

    Also it appears with Slim you shouldn't use echo. Try calling $app->response->setBody.

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办