簡體   English   中英

如何在JQuery Ajax中將JSON響應讀取為名稱/值對

[英]How to read json response as name value pairs in JQuery ajax

我想在我的JQuery代碼中將json響應讀取為名稱和值對。 這是我從dotnet代碼返回的示例JSON響應:

const string format = "\"HasCases\": \"{0}\""; 
StringBuilder json = new StringBuilder(128); 
json.Append("{"); 
json.AppendFormat(format, JSONString("true"));
json.Append("}"); 
Response.Clear(); 
Response.AppendHeader("Content-type", "application/json; charset=utf-8");                                                                               Response.Write(json.ToString()); 
Response.End();

要獲取Json值,是否需要使用Response代碼?在我的Json頁面中,我能夠將輸出獲取為HasCases:true。

這是我的JQuery代碼

<span id="testSpan" runat="server">inactive</span>
<script type="text/javascript">
inactive 
$.ajax({ 
        type: 'POST',
        url: "~/Pages/UserCaselistnonEmptyAjax.aspx", 
        dataType: "json", 
        success: function (response){
        $('#testSpan').innerHTML = response.HasCases; 
       }, 
     error: function (e1, e2, e3) {
  $('#testSpan').innerHTML = 'Error';
      }
   });
 </Script>

當我調試firebug表單時,我的控件不會轉到"$('#testSpan').innerHTML = response.HasCases; "它從循環中出來。

jQuery對象不實現.innerHTML 使用.html()代替:

$('#testSpan').html(response.HasCases);

我正在使用返回我的json

return (new JavaScriptSerializer().Serialize(request)); 

在我的C#代碼中。我正在調用該函數,以在頁面加載事件時返回此值。 輸出是這個

{"registration_ids":["1","2"],"data":{"message":"Your message","tickerText":"Your ticker","contentTitle":"Your content"}}

但是我無法使用jquery ajax讀取此返回的json fomrat我的ajax在下面

function as()
  {

                $.ajax({
                      type:"get",
                      url:"mydjson.aspx",
                      contentType: 'application/json;charset=utf-8', 
                      dataType: {'json':'datas'}, 
                      //data: JSON.stringify(request),//{ get_param: 'value' },
                      success:function (msg) {

                                         $("#table").html("<h1>" + msg+ "</h1>").fadeIn("slow");

                                    },
                                      //  function (data, status)

                     error: function (xhr, textStatus, error) 
                            {
                               var errorMessage = error || xhr.statusText;

                                $("#table").html("<h3>" + errorMessage + "</h3>").fadeIn("slow");
                            }
                   });
        return false;
   //   });

}

我收到錯誤“ Ivalid json”以及頁面“ mydjson.aspx”的內容。為此,請幫我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM