【问题标题】:Write Callback Result to Page将回调结果写入页面
【发布时间】:2014-03-13 14:14:15
【问题描述】:

我一直在寻找几个小时试图弄清楚如何将我的回调结果写入我的网页。这是一个相当具体的问题,但我遇到的任何解决方案都没有真正奏效。以下是详细信息:

伪代码:(理想情况下)

  1. 用户与网页交互(在这种情况下,更改边界 在谷歌地图内)。
  2. 在 bounds_changed 时,javascript 会抓取 限制并通过 JSON 格式的 jquery 回调将它们发送到我的 C# 代码。
  3. C#代码处理边界并将搜索结果以JSON的形式返回到网页以供javascript操作。

第 3 步的第二部分是问题点(其他一切正常)。我似乎无法在回调完成后动态地写出结果。

以下是相关代码:

从客户端向服务器发送消息:(这可行,但只是为了完整性而包含它)

function toServer(data) {
    var dataPackage = data + "~";
    jQuery('form').each(function () {
        document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
        $.ajax({
            type: "POST",
            async: true,
            url: window.location.href.toString(),
            data: jQuery(this).serialize(),
            success: function (result) {
                console.log("callback compelete");
            },
            error: function(error) {
                console.log("callback Error");
            }
        });
    });
}

页面加载时的服务器代码:(注意这不起作用[searchResults的写作])

        public Map_ResultsViewer_Beta(...)
        {
            ...

            //holds actions from page
            string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;

            // See if there were hidden requests
            if (!String.IsNullOrEmpty(payload))
            {
                //temp: process the request //2do: make this dynamic
                string temp_AggregationId = CurrentMode.Aggregation;
                string[] temp_AggregationList = temp_AggregationId.Split(' ');
                Perform_Aggregation_Search(temp_AggregationList, true, Tracer);

                //NOTHING BELOW THIS REALLY WORKS, ignore the the 'placeholder' method of displaying the results, it was just one attempt.

                #region 

                // Start to build the response
                StringBuilder mapSearchBuilder = new StringBuilder();
                PlaceHolder MainPlaceHolder = new PlaceHolder();

                mapSearchBuilder.AppendLine("  ");
                mapSearchBuilder.AppendLine("     <script type=\"text/javascript\"> ");
                mapSearchBuilder.AppendLine("     function processCallbackResult(){ ");

                if (!string.IsNullOrEmpty(HttpContext.Current.Session["SearchResultsJSON"].ToString()))
                {
                    mapSearchBuilder.AppendLine("     var searchResults=" + HttpContext.Current.Session["SearchResultsJSON"] + ";");
                }
                else
                {
                    mapSearchBuilder.AppendLine("     var searchResults; ");
                }

                mapSearchBuilder.AppendLine("     } ");
                mapSearchBuilder.AppendLine("     </script> ");
                mapSearchBuilder.AppendLine("  ");

                // Add this to the page
                Literal writeData = new Literal { Text = mapSearchBuilder.ToString() };
                MainPlaceHolder.Controls.Add(writeData);

                #endregion

            }
            else
            {
                //string temp_AggregationId = CurrentMode.Aggregation;
                //string[] temp_AggregationList = temp_AggregationId.Split(' ');
                //Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
                HttpContext.Current.Session["SearchResultsJSON"] = "";
            }

        }

实际执行搜索:(这行得通,只是为了完整起见把它放在这里)

        public void Perform_Aggregation_Search(...)
        {
            //search the database for all items in all of the provided aggregations and merge them into one datatable
            List<DataTable> temp_Tables = new List<DataTable>();
            DataTable searchResults = new DataTable();
            foreach (string aggregationId in aggregationIds)
            {
                temp_Tables.Add(Database.Get_All_Coordinate_Points_By_Aggregation(aggregationId, Tracer));
            }
            foreach (DataTable temp_Table in temp_Tables)
            {
                searchResults.Merge(temp_Table);
            }

            //assign and hold the current search result datatable, from now on we will be using this as the base layer...
            HttpContext.Current.Session["SearchResults"] = searchResults;

            //call json writer with these results
            string searchResultsJSON = Create_JSON_Search_Results_Object(searchResults,Tracer);

            //send json obj to page and tell page to read it (via callback results)
            HttpContext.Current.Session["SearchResultsJSON"] = searchResultsJSON;

        }

创建 JSON 对象的代码:(这可行,只是为了完整起见将其放在这里)

        public string Create_JSON_Search_Results_Object(...)
        {
            //take the search results from db query (incoming) and parse into JSON
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row = null;
            foreach (DataRow dr in searchResults.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in searchResults.Columns)
                {
                    row.Add(col.ColumnName.Trim(), dr[col]);
                }
                rows.Add(row);
            }
            //return JSON object
            return serializer.Serialize(rows);
        }

我错过了什么吗?我究竟做错了什么?你能指出我的写作方向吗?

再一次,问题在于将回调的结果写入页面。

谢谢!

【问题讨论】:

  • 那么您不能在 jquery 调用的 success 部分中为 DOM 上的元素设置值吗?
  • 没有。我的理解是,jquery 调用中的结果不是我的 C# 代码的实际结果(怎么可能,我没有明确返回结果-是吗?)。我尝试将结果输出到 firebug 并搜索我的 JSON,但它不存在...
  • 您期望的结果是来自Create_JSON_Search_Results_Object() 的客户端吗?
  • 我不知道。老实说,我不确定这一切是如何运作的。我将回调可视化为您基本上只是调用服务器端方法并且该方法具有返回值的地方。看来我搞错了……

标签: c# javascript jquery json callback


【解决方案1】:

您需要在您的 ajax 帖子的 success 方法中对 JSON 进行实际操作。

您可以像这样使用 JQuery 来定位 DOM 节点:

$('.example').html(result);

【讨论】:

  • 我正在尝试这个......我不完全理解结果是什么。更具体地说,它是如何得出的。在我看来,它应该是我的回调的返回值,它本身调用(并因此返回)c# 方法。我的理解似乎不是它的实际工作方式......
  • “结果”将是您发布到的 URL 上的任何数据。如果这返回一个页面,“结果”将是该页面的标记。如果该 URL 返回 JSON,则您的“结果”将是 JSON。你有没有在你的成功中输入一个控制台日志来看看你的反应是什么?
  • 是的,这没用。我添加了 $('#test_temp').html(result);成功的 jquery 但它所做的只是处理对页面引用的 js 文件的 GET 请求。我假设这只是编写我所有返回到 test_temp div 的 html。有没有办法做类似 document.getElementById('hiddenDiv_searchResults').value = result.searchResults;我在哪里只采摘我们应该说回调的改变结果吗?
  • 如你所说,我如何只返回 JSON?
  • 如果您要正常访问该 URL,您使用的 JavaScript AJAX 方法只会返回该 URL 返回的任何内容。如果需要 JSON,则需要确保 URL 是 JSON 文档。我不知道该怎么做,那将在 C# 中。如果您要返回 HTML,并且只想剥离其中的一个子集,则需要使用 JQuery 之类的东西来解析 HTML。
猜你喜欢
  • 2014-05-06
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
相关资源
最近更新 更多