簡體   English   中英

沒有Response.End()代碼無法正常工作

[英]Without Response.End() code does't works fine

我正在使用jquery ajax函數,如果將Response.End()放在服務器端,我不知道這是什么原因?

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            url: "WebForm1.aspx",
            type: "POST",
            datatype: "json",
            success: function(data) {

                alert(reuslt.CustomerID);

            }
        });
    });

在WebForm1.aspx中

protected void Page_Load(object sender, EventArgs e)
        {
            Customer c = new Customer();
            c.CustomerID = "1";
            c.ContactName = "Jhon";
            c.CompanyName = "Dell";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            String response = serializer.Serialize(c);
            Response.Write(response);
            Response.End();

          }

客戶類別

public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }

    }

您沒有使用Webmethod,這意味着de.aspx文件仍然可以響應HTML。 Response.end()結束響應,這意味着不再執行任何代碼。

您需要做的是:

在VB文件中:

[System.Web.Services.WebMethod(BufferResponse=false)]
public Customer getCustomer()
{
   //implementation code
   return new Customer(); // The code you need
}

jQuery的:

    $.ajax({
                type: "POST",
                url: "WebForm1.aspx/getCustomer", // Webmethod function here
                data: {},
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                async:false,
                success: function (json) {
                    var msg = JSON.parse(json.d);
                    alert(msg.customerID);
                },
                failure: function () {
                    alert("Sorry,there is a error!");
                }
            });

信息:

  1. 網絡方法
  2. jQuery ICM Web方法調用(stackoverflow答案)
  3. 可以通過在Google上搜索jQuery c# Webmethod找到更多信息。

UDPATE
因為Ali希望具體知道使用response.end原因,否則,它將失敗。 因為有了response.end將結束請求。 因此,不會執行任何進一步的代碼。 這意味着未呈現HTML。 如果沒有此代碼,則將呈現HTML,並將其作為響應進行響應。 這意味着JSON + HTML是請求的輸出。

將所有當前緩沖的輸出發送到客戶端,停止頁面的執行,並引發EndRequest事件。

由於Response.end引發異常(如上文文檔所述)。 最好使用HttpContext.Current.ApplicationInstance.CompleteRequest

我不知道確切的輸出結果,但是想法是您的Web表單(.aspx)使用頁面生命周期。 如果您沒有通過調用Response.End()結束生命周期,則頁面將繼續處理並將其發送到輸出流。

因此,如果您不告訴ASP.NET停止輸出到響應流,它將最終到達其渲染階段並寫出.asxp文件的內容。

如果不調用Response.End()來查看返回的內容,請嘗試使用Fiddler查看生成的response / html。

(還有@Niels所說的-我的答案更多是針對非ajax實現的)

暫無
暫無

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

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