在我的网站上,我有一个jquery手风琴插件。为了收集(来自多个表单的)所有表单数据,我使用以下行:$('#form_values').val($('form').serialize())
。然后我将数据提交到我的php文件,在本例中,该文件包含:
<?php
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
return json_encode(array("error" => "bad table name"));
?>
我希望我的json/ajax/jquery脚本会显示一个带有"坏表名"的警告框,但它只显示一个带文本的警告框:Parseerror。我的jquery脚本:
$.ajax({
type:'POST',
data:$('#form_values').val($('form').serialize()),
url:'handle.php',
dataType: "json",
success: function(data){
alert("sucesso: "+data.msg);
window.location='index.php';
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert (textStatus);}
});
我不知道这里出了什么问题。。希望有人愿意帮助我。
您需要使用serializeArray
而不是serialize
,然后将其转换为JSON字符串:
$.ajax({
type:'POST',
data:JSON.stringify($('form').serializeArray()),
url:'handle.php',
dataType: "json",
success: function(data){
alert("sucesso: "+data.msg);
window.location='index.php';
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert (textStatus);}
});
我认为,不知何故,服务器脚本不会返回json(使用firelux/其他调试工具来检查响应)。当您指定响应的类型应该是json时,您会得到一个parseerror。
编辑:您是否将表单发送到正确的url?例如/handle.php而不是handle.php?