【发布时间】:2018-02-16 05:28:19
【问题描述】:
我在这个错误上被困了一段时间,我似乎无法找到它。我收到此错误:
错误:SyntaxError:JSON 中位置 1 的意外字符串
我正在尝试使用此dashboard.js 文件向dashboard.php 发出AJAX 请求:
$(".next").click(function(){
console.log("next uitgevoerd");
i++;
huidige_pagina += 1;
document.getElementById("pagina").innerHTML = huidige_pagina;
$.ajax({
type: 'POST',
url: 'http://goad-as-05/ramon/logic/dashboard.php',
contentType: 'application/x-www-form-urlencoded',
dataType: 'JSON',
data: { "pagina": i },
success: function (resultaat) {
alert(resultaat);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + errorThrown);
}
});
});
这是 php 代码:
<?php
header("Content-Type: application/json; charset=utf-8", true);
if(isset($_POST["pagina"])){
$pageno = $_POST["pagina"];
echo $pageno;
} else {
echo "foutje";
}
// $url will contain the API endpoint
$url = "https://app.teamleader.eu/api/getContacts.php";
// $fields contains all the fields that will be POSTed
$fields = array(
"api_group"=>(GROUP_KEY),
"api_secret"=>(SECRET_KEY),
"amount"=>2,
"pageno"=>$pageno
);
// Make the POST request using Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
// Decode and display the output
$api_output = curl_exec($ch);
echo curl_error($ch);
//$json_output = json_decode($api_output);
echo json_encode($api_output);
header('application/json');
// Clean up
curl_close($ch);
?>
这是我的html:
<div class="pagina">
<p id="pagina">1</p>
</div>
我确定这不是我的 URL,因为这两个文件都在同一个文件夹中。
我必须先使用JSON.stringify("pagina":i) 并使用它吗?
感谢任何帮助,这可能是我似乎无法找到的最小错误。
找到的解决方案: 加载时用 ctrl+F5 刷新我的 javascript,完全忘记了缓存....感谢大家的帮助!
拉蒙
【问题讨论】:
-
我有一个 var i = 0;在这个函数之外
-
错误是因为返回的数据不是有效的JSON。您需要调查服务器上发生这种情况的原因。
-
您能否提供一个您从服务器获得的响应的示例(例如,如果您直接访问 URL)
-
我们需要查看您的 PHP 代码,因为 JS 本身没有任何问题
-
顺便说一下,你不需要发送
contentType,这已经是jQuery发送的默认值了
标签: javascript php jquery json ajax