0
我有这样的代码如何从serialize()解析错误和状态消息?
$(document).ready(function(){
// ...
$('form').submit(function() {
// ...
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text(
"responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
}, // error
success: function(result){
if (result.error) { // script returned error
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} // if
else { // perl script says everything is okay
$('div#create_result').text(
"result.success: " + result.success +
", result.userid: " + result.userid);
$('div#create_result').addClass("success");
} //else
} // success
}); // ajax
$('div#create_result').fadeIn();
return false;
});
});
总是提示错误信息,如果它是成功的。
例子:
responseText: Content-Type: application/json; charset=utf-8 {"success" : "Activity created", "Activity number" : "38"}, textStatus: parsererror, errorThrown: SyntaxError: JSON.parse
任何想法有什么不好?
更新:
这是我如何使服务器端Perl脚本的JSON字符串。
...
$json = qq{{"error" : "Owner $owner doesn't exist"}};
...
$json = qq{{"success" : "Activity created", "Activity number" : "$id"}};
...
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
我现在已经包含了JSON字符串。这是正确的,我使用'成功:功能(结果){'或应该是'成功:功能(数据){'? – 2011-05-09 15:03:17
您可以在您的函数中为您的参数命名参数(只要它不是保留关键字!) - 数据或结果都可以。请注意我更新的答案,问题似乎是你的JSON响应中有标题。 – 2011-05-09 15:07:10
所以'成功:函数(结果){'意味着我创建一个名为'result'的对象?我会期待'data:$(this).serialize(),'返回一个对象?这是我的第一个WebApp,所以我很新。 – 2011-05-09 15:16:03