我无法弄清楚为什么这个Ajax脚本无法运行。
下面是代码:
$(document).on('submit', '.edit_user', function(){
console.log('submit');
$.post
(
$(this).attr('action'),
$(this).serialize(),
function(data){
console.log("data");
console.log(data);
$('#edit_first_name').val(data['first_name']);
},
"json"
);
return false;
});
我在控制台中显示submit
,因此我知道.post
已被调用。我也知道它会转到return false
,因为表单永远不会提交和重定向。
然而,它永远不会console.log(data)
。
我很确定这一切都是因为我忘记了一些简单的事情。
答案 0 :(得分:1)
尝试使用.fail()
回调并查看是否返回,同时确保服务器正确发送json标头或$.post
将失败。
$(document).on('submit', '.edit_user', function(){
console.log('submit');
var jqXHR = $.post($(this).attr('action'), $(this).serialize(),
function(data){
console.log("data");
console.log(data);
$('#edit_first_name').val(data['first_name']);
},
"json"
);
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {
console.log('error', textStatus, errorThrown);
});
return false;
});
如果您使用的是PHP,请确保在任何其他输出之前打印了正确的标题。
<?php
header('Content-type: application/json');
....code...
echo json_encode(some_array);
答案 1 :(得分:0)
您定义的功能是成功回调。确保您当前的帖子从服务器返回成功的响应。或者将.post()
调用转换为.ajax()
调用并定义失败calback
答案 2 :(得分:0)
使用此,
$(document).on('submit', '.edit_user', function(e){
e.preventDefault();
console.log('submit');
$.post
(
$(this).attr('action'),
$(this).serialize(),
function(data){
console.log("data");
console.log(data);
$('#edit_first_name').val(data['first_name']);
},
"json"
);
return false;
});
使用preventDefault函数来防止提交的默认行为。 此外,.edit_user应该是表单元素的类
答案 3 :(得分:-1)
你的javascript记录器会给你什么回报吗?