2011-05-09 23 views
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; 

回答

3

此:

parseError, 
SyntaxError: JSON.parse 

您迴應JSON是不能接受的分析器,它可能是畸形的。您發佈的responseText中有頭,那些不應該存在:

Content-Type: application/json; charset=utf-8 {"success" : "Activity created", "Activity number" : "38"} 
+0

我現在已經包含了JSON字符串。這是正確的,我使用'成功:功能(結果){'或應該是'成功:功能(數據){'? – 2011-05-09 15:03:17

+2

您可以在您的函數中爲您的參數命名參數(只要它不是保留關鍵字!) - 數據或結果都可以。請注意我更新的答案,問題似乎是你的JSON響應中有標題。 – 2011-05-09 15:07:10

+0

所以'成功:函數(結果){'意味着我創建一個名爲'result'的對象?我會期待'data:$(this).serialize(),'返回一個對象?這是我的第一個WebApp,所以我很新。 – 2011-05-09 15:16:03

3

考慮使用Perl's JSON module,它處理序列化和解析爲您服務。有一個XS後端(用於速度),以及一個PP(純Perl)後端。

相關問題