【发布时间】:2016-04-05 23:10:05
【问题描述】:
当我尝试从 php 脚本获取数据时遇到问题,我收到此错误
Uncaught SyntaxError: Unexpected token <
当我打开 php 脚本的链接时,我的 ajax 请求有效,但是当我删除浏览器的缓存时,问题又出现了!
这是我的 JavaScript 代码:
$.ajax({
url : "http://xxxxx/xxxx/xxxx.php?callback=test",
type : "GET",
dataType : "jsonp",
jsonpCallback: "test",
contentType: "application/javascript",
async: true,
success : function(data) {
console.log("success");
},
error : function(request, status, error) {
console.log(error);
}
});
这是 PHP 代码:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept,Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');
test_function();
function test_function(){
$return = array("reponse"=>"false");
try {
include_once $_SERVER['DOCUMENT_ROOT'].'/bd/db_connect.php';
$db = new DB_CONNECT();
$con = $db->connect();
$sql = "SELECT * FROM `xxx` ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$response ['reponse']="true";
$response["data"] = array();
while ($row = $result->fetch_assoc()) {
$rest = array();
$rest["xxx"] = $row["xxx"];
$rest["xxx"] = $row["xxx"];
array_push($response["data"], $rest);
}
} else {
$response ['reponse']="false";
}
} catch (Exception $e) {
$response ['reponse']="false";
}
echo $_GET['callback'] ."(".json_encode($response).")";
//echo "(".json_encode($response).")";
}?>
我在回复中得到了这个。 Link to image
【问题讨论】:
-
我猜其他网站需要设置某种 cookie。如果没有设置,你会得到一个 http 错误页面,在你的 JS 中会导致看到的错误
-
问题出在 PHP 脚本上,而不是 javascript。你能展示一下代码吗?
-
听起来 PHP 脚本并没有真正实现 JSONP。它应该发回看起来像
test({...});的 Javascript。 -
contentType: "application/javascript"是错误的。该标头适用于您在发布数据中发送的数据类型。由于您使用的是GET,而不是POST,因此没有内容。 -
在这一行中,您向 json 字符串添加一些原始文本,使其格式不同,并且输出不再是 json : echo $_GET['callback'] ."(".json_encode($响应)。")";
标签: javascript php jquery ajax