gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:51:22 24 4
gpt4 key购买 nike

我的 php 脚本和 javascript 文件之间的通信有一些问题。 javascript 似乎正在从我编写的 php 脚本中接收 html、json 和“无效的 json”。

在 Javascript 代码中,data 变量计算为:

{"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 ...."}

这不是因为我的代码中有任何 console.log 语句而打印,这是由于 Firefox 从 GET http://...../.php 自动控制台输入的结果。打电话。

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

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

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

SyntaxError: expected expression, got '<' --> file.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
})

;

关于javascript - 为什么我的带有 JSONP 脚本的 PHP/AJAX 返回 HTML、JSON 和无效的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44681624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com