簡體   English   中英

如何處理jSON XMLHttpRequest響應?

[英]How to handle jSON XMLHttpRequest response?

我正在嘗試控制發送回客戶端的json響應,但不知道具體如何。這是一個簡單的演示:

js代碼

xhr = new XMLHttpRequest();
xhr.open("POST", "page.aspx", true);
xhr.send();

// handle the response with xhr.responseText

.cs代碼

    bool success = false;
    string message = String.Empty;

    // Create JSON Response
    var jsonData = new
    {
        success = success,
        message = message
    };

    Response.Write(jsonData);    

問題是當我查看xhr.responseText時,我看到:

"{ success = False, message = } 
<!DOCTYPE html PUBLIC ....
....
..
"

您需要Response.Clear()Response.Write之前清除Response.Write

您想要在寫入jsonData之后執行Response.Clear(),然后執行Response.End()。

然后,您需要在javascript中處理JSON響應。 我推薦Crockford的JSON庫

我還建議使用jQuery的$ .ajax()函數,而不要手動滾動自己的XHR調用。

PS。 最好對ASPX頁面上聲明的ASHX資源或PageMethods / WebMethods進行Ajax調用。 更妙的是,放棄Web表單,將ASP.NET MVC與從Controller返回的JsonResults一起使用。

PPS。 如果您最終使用WebMethods,那么本文非常出色。

您的CS代碼未生成有效的JSON(除了在JSON數據之后顯示其他內容之外)。 所有JSON描述符必須雙引號,任何字符串值也必須雙引號。 值與其描述符之間用冒號分隔。 示例:{“成功”:否,“消息”:“沒有用”}。

請訪問http://json.org/ ,以了解用於特定語言的庫。

暫無
暫無

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

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