我正在尝试通过 Ajax 调用提醒一些数据。谁能发现我做错了什么吗?
PHP
while($row = $stmt->fetch()){
echo json_encode($row);
}
echo "Done!";
Json_encode/网络预览的结果
{"flakId":"21098-10_flak-2"}{"flakId":"21098-10_flak-1"}Done!
JS
if(chosenObjNr){
alert('I CAN see this alert')
$.ajax({
url:'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
error: function (data){ alert("failed, i can see this!");},
success: function(data){
alert('I cannot see this alert!');
alert(data);
var data0;
data0 = data[0];
alert(data0);
var falkId;
flakId = data[0];
alert(flakId);
console.log(data);
}
});
};
结果
没有警报,控制台中也没有任何内容。
最佳答案
问题是,ajax 的 success
部分永远不会运行。您将 dataType
定义为 json,因此它需要 json。你的 PHP 是 echos 2 json 和一个不需要的字符串。
因此,要检查您的错误是什么,请在评论中添加 fail
函数,如 Sina Sad:
if (chosenObjNr) {
alert('I CAN see this alert')
$.ajax({
url: 'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
}).done(function (data) {
alert('I cannot see this alert!');
//Do what you want to do here
}).fail(function (msg) {
alert('An error occured: ' + msg.statusText);
});
}
而且,如果您想修复 .php
,请删除 echo 'Done';
部分,并将记录添加到数组中,完成后进行编码转为 json:
$return = array();
while ($row = $stmt->fetch()) {
$return[] = $row;
}
echo json_encode($return);
关于javascript - Ajax 调用没有警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710609/