我正在使用下面的代码从远程地址获取 json 并将其信息用作我的项目中的 javascript 对象。
$.ajax({
type: "POST",
dataType: "JSONP",
url: "http://www.edupal.co/deals/?email=wed@umbc.edu",
jsonCallback: 'parseResponse',
success: function( data ){
console.log($.parseJSON(data));
},
error: function( xhr, str, e ){
console.log( "There was an error with the request", str, e );
},
complete: function(){
console.log("The request has completed.... finally.");
}
});
问题是,尽管请求正常(我可以在开发工具的网络选项卡中看到它),但它在我的 javascript 控制台中告诉我有一个“意外 token :”
这是返回的 JSON:
{"0":"1","id":"1","1":"20% Off UMBC Hoodies","title":"20% Off UMBC Hoodies","2":"umbc","school":"umbc","3":"UMBC Bookstore","location":"UMBC Bookstore","4":"http:\/\/bookstore.umbc.edu\/StoreImages\/9-862269-1.jpg","picture":"http:\/\/bookstore.umbc.edu\/StoreImages\/9-862269-1.jpg","5":"Limit 1 per person. Must present EduPal app with deal to cashier to be awarded discount.","description":"Limit 1 per person. Must present EduPal app with deal to cashier to be awarded discount.","6":"http:\/\/www.globatum.com","link":"http:\/\/www.globatum.com","7":"7\/30\/2014,08:45","start":"7\/30\/2014,08:45","8":"7\/30\/2014,09:45","end":"7\/30\/2014,09:45","9":"active","status":"active","10":"0","clicks":"0","11":"2014-07-30 20:18:30","posted":"2014-07-30 20:18:30"}
所以我对问题可能出在哪里感到困惑。谁能帮忙?如果有人想测试它,我把它全部放在 jsfiddle 中。 http://jsfiddle.net/#&togetherjs=T0ztQQbitP
这是生成 JSON 的 PHP
<?php
include('../dbconnect.php');
header('Content-Type: application/json');
$email = $_GET['email'];
$email = substr($email, 0, strpos($email, ".edu"));
$email = strstr($email, '@');
$school = str_replace('@', '', $email);
$sql = "SELECT * FROM `ads` WHERE `school` = '$school' ORDER BY `posted` DESC";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count > 0){
$deals = array();
$deals = mysql_fetch_array($result);
echo json_encode($deals) ;
}
else{
echo 'No records';
}
?>
最佳答案
格式不正确。
JSONP 必须是一个 JavaScript 程序,由单个函数调用组成(对查询字符串中指定的函数(通常通过 callback
参数)传递一个参数(通常是对象或数组文字) .
您引用的响应包含一个 JavaScript 对象文字。由于属性名称是标识符而不是字符串,因此它甚至不是 JSON。由于您在键值对之间缺少 ,
,因此它甚至不是有效的 JavaScript。
当我点击该 URL 时,我得到的实际响应(看起来您是从 JSON 的 Chrome 可视化而不是源代码复制/粘贴)是 JSON — 但不是 JSONP。所以你不应该告诉 jQuery 将它作为 JSONP 处理。
由于 URL 似乎没有通过 CORS 授予权限,因此似乎没有任何方法可以直接使用客户端 JavaScript 访问它,除非您将 HTML 托管在 www.edual.co
所以你需要使用一些服务器端代码将数据中继到你的 JS。
关于javascript - 为什么在我的 json 格式正确时使用 $.ajax() 时 jsonp 返回 "Unexpected Token :"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25063169/