2011-11-21 76 views
2

我有一個頁面,可以快速登錄並訪問某個JSON數據的Web服務。數據它返回這個樣子的:使用jquery解析JSON

{ 'RESPONSE' : 'INVALID','CAMPAIGNID' : '0','MORELINK' : '' } 

的代碼我用得到這些數據,並試圖彈出基於信息的模式窗口是:

$.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      url: "Login.asmx/Logon", 
      data: strData, 
      dataType: "json", 
      success: function (response) { 
       $('#divResp').html(response.d); 
       $(response.d).each(function(index,item){ 
        alert(item.campaignid); 
       }); 
       if (res.indexOf('invalid') >= 0){      
        //invalid account information UNP      
        foo = "You entered an invalid account number or password"; 
        showDialog('screenActivate.asp',test_imgName); 
       } 
       if (res.indexOf('none') >=0) { 
        //do not deliver splash screen 
        foo = "No splash screen for YOU!"; 
       } 
       if (res.indexOf('error') >=0) { 
        //general error 
        foo = "You entered an error"; 
       } 
       if (res.indexOf('frozen') >=0) { 
        //member is locked out from numberous failed attempts 
        foo = "You have too many failed attempts. Your account has been locked"; 
       } 
       if (res.indexOf('.png') >=0) { 
        imgName = (response.d); 
        showDialog('screenActivate.asp',test_imgName); 
       } 
       alert(foo); 
       $('#divResp').html(response.d); 
      } 
     }); 
     $('#divQuery').ajaxError(function(evt, request, settings){ 
      $('#divResp').html("Web services timeout. Please try again.");    
     }); 
    } 

面臨的挑戰是,無論是我沒有得到任何信息(未定義)或與本次迭代,從Firebug的錯誤,指出未捕獲的異常:語法錯誤,無法識別的表情:「無效」

我不是正確解析JSON響應?

相關評論回答

我貼:"d":"{ 'RESPONSE' : 'INVALID','CAMPAIGNID' : '0','MORELINK' : '' } "到jsonlint.com和工具說,JSON是有效的。當我試圖通過response.d與每個語句循環時,它似乎逐字符。

+1

總是首先驗證repsonse,例如,與http://www.jsonlint.com。在你的情況下,你絕對沒有得到有效的JSON。 – Daff

回答

6

JSON規範要求使用雙引號("),而不是單引號('

官方JSON字符串解析圖(從http://www.json.org

響應您的評論...

好吧,這裏的交易...

"d":"{ 'RESPONSE' : 'INVALID','CAMPAIGNID' : '0','MORELINK' : '' } " 

是有效的JSON ...但它是簡單地用一個包含字符串d屬性的對象...

"{ 'RESPONSE' : 'INVALID','CAMPAIGNID' : '0','MORELINK' : '' } " 

數據,將工作你希望是這樣的方式.. 。

{"d": {"RESPONSE":"INVALID","CAMPAIGNID":"0","MORELINK":""}} 
+0

我在jsonlint.com上粘貼了「d」:「{'RESPONSE':'INVALID','CAMPAIGNID':'0','MORELINK':''}」,該工具表示JSON有效。當我試圖通過每個語句循環response.d時,它似乎逐字符。 – techmaniac

+0

@ user1058635答案已更新。 – jondavidjohn

+0

好吧,我有正確編碼的JSON,但我仍然沒有遍歷該對象並獲取名稱/值對。如果我警告返回它只是給我對象[object]如何確定JSON內容?我想知道這個campaignid,如果有更多的鏈接。 – techmaniac

1

除了@jondavidjohn's answer(+1),你還引用變量res,這是沒有定義的。

+0

我在解決JSON數據問題時刪除了res的聲明。警報()是正確的。 :) – techmaniac