为什么我的 PHP/AJAX 和 JSONP 脚本返回 HTML、JSON 和无效的 JSON?



我的php脚本和javascript文件之间的通信遇到了一些问题。 似乎javascript正在从我编写的php脚本中接收html,json和"无效json"。

在 Javascript 代码中,数据变量的计算结果为:

{"readyState":4,"status

":200,"statusText":"success"}

这不是我在下面回显的 JSON 格式(在我这样做的代码中的任何位置)。 根据我的研究,这是因为 PHP 代码中的 JSON 回显返回了无效的 JSON(这导致 PHP 返回此结果)。 但是,当我检查控制台时,我发现以下内容:

<br />
<b>Warning</b>:  mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for ... in <b>..../.php</b> on line <b>xx</b><br />
{"status":"failure","message":"Access denied for ...."}

由于我的代码中的任何控制台.log语句,这不会打印出来,这是由于 Firefox 从 GET http://...../.php 调用中自动进入控制台而打印的。

第一行代码是 PHP 将返回的 html,如果这不是 JSON 返回,上面代码的底行是我创建的实际 JSON 对象,并且我想使用它。

我在这里发帖的原因是我想不出为什么 PHP 会返回 html、我的 JSON 和 JSON 指示无效的 JSON。

我还应该提到我在控制台上收到另一个错误:

语法错误:预期的表达式,得到"<" -->文件.php:1

这向我表明浏览器出于某种原因试图解释客户端上的 php,但我不确定这是否准确。

我认为我在某处有一个错误,这是所有这些症状的根源,但是经过一段时间和研究,我无法自己找到这个错误。

我使用的代码如下所示:

Javascript AJAX:

$.ajax({
url: "...url.../file.php",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: {
name: email,
email: email
},
complete: function(data) {
console.log(JSON.stringify(data));
//this is where the {"readyState":4,"status":200,"statusText":"success"} appears
}
});

PHP(内容缩小到此问题的范围):

<?php
header("Content-type: application/json");
header("Content-Disposition: attachment;Filename="gamesUser.json"");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
.........
$data = array();
$conn = @new mysqli($servername, $username, $password, $dbname, $port);
//check the connection
if ($conn->connect_error) {
$data['status'] = 'failure';
$data['message'] = $conn->connect_error;
echo json_encode($data);
} else {
.........
$data['status'] = 'success';
$data['message'] = 'operations complete';
$data['fileURL'] = $fileURL;
echo json_encode($data);
.........
}
.........
?>

解决!

代码:

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

以及更改 AJAX 参数:

type: "GET",
dataType: 'jsonp',
jsonpCallback: 'handleResponse',
data: data

已修复问题。 感谢所有协助讨论的人。

我想,你需要的是jsonpcallback函数,请通过下面的例子,你会明白的

function myfunc(json) {
alert(json);
}
$.ajax({
type: "GET",
url: "http://example.com?keyword=r&callback=jsonp",
dataType: 'jsonp',
jsonpCallback: 'myfunc', // the function to call
jsonp: 'callback', // name of the var specifying the callback in the request
})

;

当 PHP 中发生错误时,它会使用 HTML 显示错误信息,以便您可以在浏览器中正确查看它。这就是为什么你会得到意外的HTML,所以你应该确保PHP脚本不会显示错误。

您可以通过在 (@符号前面加上 at ( ) 符号来抑制 mysqli 构造函数的警告(我认为这是导致问题的那个):

... @mysqli(...) ...

还有其他方法可以避免显示错误,请检查 http://php.net/manual/es/errorfunc.configuration.php#ini.display-errors http://php.net/manual/es/errorfunc.configuration.php#ini.error-reporting

最新更新